pugixml.cpp 256 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250
  1. /**
  2. * pugixml parser - version 1.2
  3. * --------------------------------------------------------
  4. * Copyright (C) 2006-2012, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  5. * Report bugs and download new versions at http://pugixml.org/
  6. *
  7. * This library is distributed under the MIT License. See notice at the end
  8. * of this file.
  9. *
  10. * This work is based on the pugxml parser, which is:
  11. * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
  12. */
  13. #ifndef SOURCE_PUGIXML_CPP
  14. #define SOURCE_PUGIXML_CPP
  15. #include "plisthpp/pugixml.hpp"
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <assert.h>
  20. #include <wchar.h>
  21. #ifndef PUGIXML_NO_XPATH
  22. # include <math.h>
  23. # include <float.h>
  24. # ifdef PUGIXML_NO_EXCEPTIONS
  25. # include <setjmp.h>
  26. # endif
  27. #endif
  28. #ifndef PUGIXML_NO_STL
  29. # include <istream>
  30. # include <ostream>
  31. # include <string>
  32. #endif
  33. // For placement new
  34. #include <new>
  35. #ifdef _MSC_VER
  36. # pragma warning(push)
  37. # pragma warning(disable: 4127) // conditional expression is constant
  38. # pragma warning(disable: 4324) // structure was padded due to __declspec(align())
  39. # pragma warning(disable: 4611) // interaction between '_setjmp' and C++ object destruction is non-portable
  40. # pragma warning(disable: 4702) // unreachable code
  41. # pragma warning(disable: 4996) // this function or variable may be unsafe
  42. # pragma warning(disable: 4793) // function compiled as native: presence of '_setjmp' makes a function unmanaged
  43. #endif
  44. #ifdef __INTEL_COMPILER
  45. # pragma warning(disable: 177) // function was declared but never referenced
  46. # pragma warning(disable: 279) // controlling expression is constant
  47. # pragma warning(disable: 1478 1786) // function was declared "deprecated"
  48. # pragma warning(disable: 1684) // conversion from pointer to same-sized integral type
  49. #endif
  50. #if defined(__BORLANDC__) && defined(PUGIXML_HEADER_ONLY)
  51. # pragma warn -8080 // symbol is declared but never used; disabling this inside push/pop bracket does not make the warning go away
  52. #endif
  53. #ifdef __BORLANDC__
  54. # pragma option push
  55. # pragma warn -8008 // condition is always false
  56. # pragma warn -8066 // unreachable code
  57. #endif
  58. #ifdef __SNC__
  59. // Using diag_push/diag_pop does not disable the warnings inside templates due to a compiler bug
  60. # pragma diag_suppress=178 // function was declared but never referenced
  61. # pragma diag_suppress=237 // controlling expression is constant
  62. #endif
  63. // Inlining controls
  64. #if defined(_MSC_VER) && _MSC_VER >= 1300
  65. # define PUGI__NO_INLINE __declspec(noinline)
  66. #elif defined(__GNUC__)
  67. # define PUGI__NO_INLINE __attribute__((noinline))
  68. #else
  69. # define PUGI__NO_INLINE
  70. #endif
  71. // Simple static assertion
  72. #define PUGI__STATIC_ASSERT(cond) { static const char condition_failed[(cond) ? 1 : -1] = {0}; (void)condition_failed[0]; }
  73. // Digital Mars C++ bug workaround for passing char loaded from memory via stack
  74. #ifdef __DMC__
  75. # define PUGI__DMC_VOLATILE volatile
  76. #else
  77. # define PUGI__DMC_VOLATILE
  78. #endif
  79. // Borland C++ bug workaround for not defining ::memcpy depending on header include order (can't always use std::memcpy because some compilers don't have it at all)
  80. #if defined(__BORLANDC__) && !defined(__MEM_H_USING_LIST)
  81. using std::memcpy;
  82. using std::memmove;
  83. #endif
  84. // In some environments MSVC is a compiler but the CRT lacks certain MSVC-specific features
  85. #if defined(_MSC_VER) && !defined(__S3E__)
  86. # define PUGI__MSVC_CRT_VERSION _MSC_VER
  87. #endif
  88. #ifdef PUGIXML_HEADER_ONLY
  89. # define PUGI__NS_BEGIN namespace pugi { namespace impl {
  90. # define PUGI__NS_END } }
  91. # define PUGI__FN inline
  92. # define PUGI__FN_NO_INLINE inline
  93. #else
  94. # if defined(_MSC_VER) && _MSC_VER < 1300 // MSVC6 seems to have an amusing bug with anonymous namespaces inside namespaces
  95. # define PUGI__NS_BEGIN namespace pugi { namespace impl {
  96. # define PUGI__NS_END } }
  97. # else
  98. # define PUGI__NS_BEGIN namespace pugi { namespace impl { namespace {
  99. # define PUGI__NS_END } } }
  100. # endif
  101. # define PUGI__FN
  102. # define PUGI__FN_NO_INLINE PUGI__NO_INLINE
  103. #endif
  104. // uintptr_t
  105. #if !defined(_MSC_VER) || _MSC_VER >= 1600
  106. # include <stdint.h>
  107. #else
  108. # ifndef _UINTPTR_T_DEFINED
  109. // No native uintptr_t in MSVC6 and in some WinCE versions
  110. typedef size_t uintptr_t;
  111. #define _UINTPTR_T_DEFINED
  112. # endif
  113. PUGI__NS_BEGIN
  114. typedef unsigned __int8 uint8_t;
  115. typedef unsigned __int16 uint16_t;
  116. typedef unsigned __int32 uint32_t;
  117. PUGI__NS_END
  118. #endif
  119. // Memory allocation
  120. PUGI__NS_BEGIN
  121. PUGI__FN void* default_allocate(size_t size)
  122. {
  123. return malloc(size);
  124. }
  125. PUGI__FN void default_deallocate(void* ptr)
  126. {
  127. free(ptr);
  128. }
  129. template <typename T>
  130. struct xml_memory_management_function_storage
  131. {
  132. static allocation_function allocate;
  133. static deallocation_function deallocate;
  134. };
  135. template <typename T> allocation_function xml_memory_management_function_storage<T>::allocate = default_allocate;
  136. template <typename T> deallocation_function xml_memory_management_function_storage<T>::deallocate = default_deallocate;
  137. typedef xml_memory_management_function_storage<int> xml_memory;
  138. PUGI__NS_END
  139. // String utilities
  140. PUGI__NS_BEGIN
  141. // Get string length
  142. PUGI__FN size_t strlength(const char_t* s)
  143. {
  144. assert(s);
  145. #ifdef PUGIXML_WCHAR_MODE
  146. return wcslen(s);
  147. #else
  148. return strlen(s);
  149. #endif
  150. }
  151. // Compare two strings
  152. PUGI__FN bool strequal(const char_t* src, const char_t* dst)
  153. {
  154. assert(src && dst);
  155. #ifdef PUGIXML_WCHAR_MODE
  156. return wcscmp(src, dst) == 0;
  157. #else
  158. return strcmp(src, dst) == 0;
  159. #endif
  160. }
  161. // Compare lhs with [rhs_begin, rhs_end)
  162. PUGI__FN bool strequalrange(const char_t* lhs, const char_t* rhs, size_t count)
  163. {
  164. for (size_t i = 0; i < count; ++i)
  165. if (lhs[i] != rhs[i])
  166. return false;
  167. return lhs[count] == 0;
  168. }
  169. #ifdef PUGIXML_WCHAR_MODE
  170. // Convert string to wide string, assuming all symbols are ASCII
  171. PUGI__FN void widen_ascii(wchar_t* dest, const char* source)
  172. {
  173. for (const char* i = source; *i; ++i) *dest++ = *i;
  174. *dest = 0;
  175. }
  176. #endif
  177. PUGI__NS_END
  178. #if !defined(PUGIXML_NO_STL) || !defined(PUGIXML_NO_XPATH)
  179. // auto_ptr-like buffer holder for exception recovery
  180. PUGI__NS_BEGIN
  181. struct buffer_holder
  182. {
  183. void* data;
  184. void (*deleter)(void*);
  185. buffer_holder(void* data_, void (*deleter_)(void*)): data(data_), deleter(deleter_)
  186. {
  187. }
  188. ~buffer_holder()
  189. {
  190. if (data) deleter(data);
  191. }
  192. void* release()
  193. {
  194. void* result = data;
  195. data = 0;
  196. return result;
  197. }
  198. };
  199. PUGI__NS_END
  200. #endif
  201. PUGI__NS_BEGIN
  202. static const size_t xml_memory_page_size =
  203. #ifdef PUGIXML_MEMORY_PAGE_SIZE
  204. PUGIXML_MEMORY_PAGE_SIZE
  205. #else
  206. 32768
  207. #endif
  208. ;
  209. static const uintptr_t xml_memory_page_alignment = 32;
  210. static const uintptr_t xml_memory_page_pointer_mask = ~(xml_memory_page_alignment - 1);
  211. static const uintptr_t xml_memory_page_name_allocated_mask = 16;
  212. static const uintptr_t xml_memory_page_value_allocated_mask = 8;
  213. static const uintptr_t xml_memory_page_type_mask = 7;
  214. struct xml_allocator;
  215. struct xml_memory_page
  216. {
  217. static xml_memory_page* construct(void* memory)
  218. {
  219. if (!memory) return 0; //$ redundant, left for performance
  220. xml_memory_page* result = static_cast<xml_memory_page*>(memory);
  221. result->allocator = 0;
  222. result->memory = 0;
  223. result->prev = 0;
  224. result->next = 0;
  225. result->busy_size = 0;
  226. result->freed_size = 0;
  227. return result;
  228. }
  229. xml_allocator* allocator;
  230. void* memory;
  231. xml_memory_page* prev;
  232. xml_memory_page* next;
  233. size_t busy_size;
  234. size_t freed_size;
  235. char data[1];
  236. };
  237. struct xml_memory_string_header
  238. {
  239. uint16_t page_offset; // offset from page->data
  240. uint16_t full_size; // 0 if string occupies whole page
  241. };
  242. struct xml_allocator
  243. {
  244. xml_allocator(xml_memory_page* root): _root(root), _busy_size(root->busy_size)
  245. {
  246. }
  247. xml_memory_page* allocate_page(size_t data_size)
  248. {
  249. size_t size = offsetof(xml_memory_page, data) + data_size;
  250. // allocate block with some alignment, leaving memory for worst-case padding
  251. void* memory = xml_memory::allocate(size + xml_memory_page_alignment);
  252. if (!memory) return 0;
  253. // align upwards to page boundary
  254. void* page_memory = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(memory) + (xml_memory_page_alignment - 1)) & ~(xml_memory_page_alignment - 1));
  255. // prepare page structure
  256. xml_memory_page* page = xml_memory_page::construct(page_memory);
  257. page->memory = memory;
  258. page->allocator = _root->allocator;
  259. return page;
  260. }
  261. static void deallocate_page(xml_memory_page* page)
  262. {
  263. xml_memory::deallocate(page->memory);
  264. }
  265. void* allocate_memory_oob(size_t size, xml_memory_page*& out_page);
  266. void* allocate_memory(size_t size, xml_memory_page*& out_page)
  267. {
  268. if (_busy_size + size > xml_memory_page_size) return allocate_memory_oob(size, out_page);
  269. void* buf = _root->data + _busy_size;
  270. _busy_size += size;
  271. out_page = _root;
  272. return buf;
  273. }
  274. void deallocate_memory(void* ptr, size_t size, xml_memory_page* page)
  275. {
  276. if (page == _root) page->busy_size = _busy_size;
  277. assert(ptr >= page->data && ptr < page->data + page->busy_size);
  278. (void)!ptr;
  279. page->freed_size += size;
  280. assert(page->freed_size <= page->busy_size);
  281. if (page->freed_size == page->busy_size)
  282. {
  283. if (page->next == 0)
  284. {
  285. assert(_root == page);
  286. // top page freed, just reset sizes
  287. page->busy_size = page->freed_size = 0;
  288. _busy_size = 0;
  289. }
  290. else
  291. {
  292. assert(_root != page);
  293. assert(page->prev);
  294. // remove from the list
  295. page->prev->next = page->next;
  296. page->next->prev = page->prev;
  297. // deallocate
  298. deallocate_page(page);
  299. }
  300. }
  301. }
  302. char_t* allocate_string(size_t length)
  303. {
  304. // allocate memory for string and header block
  305. size_t size = sizeof(xml_memory_string_header) + length * sizeof(char_t);
  306. // round size up to pointer alignment boundary
  307. size_t full_size = (size + (sizeof(void*) - 1)) & ~(sizeof(void*) - 1);
  308. xml_memory_page* page;
  309. xml_memory_string_header* header = static_cast<xml_memory_string_header*>(allocate_memory(full_size, page));
  310. if (!header) return 0;
  311. // setup header
  312. ptrdiff_t page_offset = reinterpret_cast<char*>(header) - page->data;
  313. assert(page_offset >= 0 && page_offset < (1 << 16));
  314. header->page_offset = static_cast<uint16_t>(page_offset);
  315. // full_size == 0 for large strings that occupy the whole page
  316. assert(full_size < (1 << 16) || (page->busy_size == full_size && page_offset == 0));
  317. header->full_size = static_cast<uint16_t>(full_size < (1 << 16) ? full_size : 0);
  318. // round-trip through void* to avoid 'cast increases required alignment of target type' warning
  319. // header is guaranteed a pointer-sized alignment, which should be enough for char_t
  320. return static_cast<char_t*>(static_cast<void*>(header + 1));
  321. }
  322. void deallocate_string(char_t* string)
  323. {
  324. // this function casts pointers through void* to avoid 'cast increases required alignment of target type' warnings
  325. // we're guaranteed the proper (pointer-sized) alignment on the input string if it was allocated via allocate_string
  326. // get header
  327. xml_memory_string_header* header = static_cast<xml_memory_string_header*>(static_cast<void*>(string)) - 1;
  328. // deallocate
  329. size_t page_offset = offsetof(xml_memory_page, data) + header->page_offset;
  330. xml_memory_page* page = reinterpret_cast<xml_memory_page*>(static_cast<void*>(reinterpret_cast<char*>(header) - page_offset));
  331. // if full_size == 0 then this string occupies the whole page
  332. size_t full_size = header->full_size == 0 ? page->busy_size : header->full_size;
  333. deallocate_memory(header, full_size, page);
  334. }
  335. xml_memory_page* _root;
  336. size_t _busy_size;
  337. };
  338. PUGI__FN_NO_INLINE void* xml_allocator::allocate_memory_oob(size_t size, xml_memory_page*& out_page)
  339. {
  340. const size_t large_allocation_threshold = xml_memory_page_size / 4;
  341. xml_memory_page* page = allocate_page(size <= large_allocation_threshold ? xml_memory_page_size : size);
  342. out_page = page;
  343. if (!page) return 0;
  344. if (size <= large_allocation_threshold)
  345. {
  346. _root->busy_size = _busy_size;
  347. // insert page at the end of linked list
  348. page->prev = _root;
  349. _root->next = page;
  350. _root = page;
  351. _busy_size = size;
  352. }
  353. else
  354. {
  355. // insert page before the end of linked list, so that it is deleted as soon as possible
  356. // the last page is not deleted even if it's empty (see deallocate_memory)
  357. assert(_root->prev);
  358. page->prev = _root->prev;
  359. page->next = _root;
  360. _root->prev->next = page;
  361. _root->prev = page;
  362. }
  363. // allocate inside page
  364. page->busy_size = size;
  365. return page->data;
  366. }
  367. PUGI__NS_END
  368. namespace pugi
  369. {
  370. /// A 'name=value' XML attribute structure.
  371. struct xml_attribute_struct
  372. {
  373. /// Default ctor
  374. xml_attribute_struct(impl::xml_memory_page* page): header(reinterpret_cast<uintptr_t>(page)), name(0), value(0), prev_attribute_c(0), next_attribute(0)
  375. {
  376. }
  377. uintptr_t header;
  378. char_t* name; ///< Pointer to attribute name.
  379. char_t* value; ///< Pointer to attribute value.
  380. xml_attribute_struct* prev_attribute_c; ///< Previous attribute (cyclic list)
  381. xml_attribute_struct* next_attribute; ///< Next attribute
  382. };
  383. /// An XML document tree node.
  384. struct xml_node_struct
  385. {
  386. /// Default ctor
  387. /// \param type - node type
  388. xml_node_struct(impl::xml_memory_page* page, xml_node_type type): header(reinterpret_cast<uintptr_t>(page) | (type - 1)), parent(0), name(0), value(0), first_child(0), prev_sibling_c(0), next_sibling(0), first_attribute(0)
  389. {
  390. }
  391. uintptr_t header;
  392. xml_node_struct* parent; ///< Pointer to parent
  393. char_t* name; ///< Pointer to element name.
  394. char_t* value; ///< Pointer to any associated string data.
  395. xml_node_struct* first_child; ///< First child
  396. xml_node_struct* prev_sibling_c; ///< Left brother (cyclic list)
  397. xml_node_struct* next_sibling; ///< Right brother
  398. xml_attribute_struct* first_attribute; ///< First attribute
  399. };
  400. }
  401. PUGI__NS_BEGIN
  402. struct xml_document_struct: public xml_node_struct, public xml_allocator
  403. {
  404. xml_document_struct(xml_memory_page* page): xml_node_struct(page, node_document), xml_allocator(page), buffer(0)
  405. {
  406. }
  407. const char_t* buffer;
  408. };
  409. inline xml_allocator& get_allocator(const xml_node_struct* node)
  410. {
  411. assert(node);
  412. return *reinterpret_cast<xml_memory_page*>(node->header & xml_memory_page_pointer_mask)->allocator;
  413. }
  414. PUGI__NS_END
  415. // Low-level DOM operations
  416. PUGI__NS_BEGIN
  417. inline xml_attribute_struct* allocate_attribute(xml_allocator& alloc)
  418. {
  419. xml_memory_page* page;
  420. void* memory = alloc.allocate_memory(sizeof(xml_attribute_struct), page);
  421. return new (memory) xml_attribute_struct(page);
  422. }
  423. inline xml_node_struct* allocate_node(xml_allocator& alloc, xml_node_type type)
  424. {
  425. xml_memory_page* page;
  426. void* memory = alloc.allocate_memory(sizeof(xml_node_struct), page);
  427. return new (memory) xml_node_struct(page, type);
  428. }
  429. inline void destroy_attribute(xml_attribute_struct* a, xml_allocator& alloc)
  430. {
  431. uintptr_t header = a->header;
  432. if (header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(a->name);
  433. if (header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(a->value);
  434. alloc.deallocate_memory(a, sizeof(xml_attribute_struct), reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask));
  435. }
  436. inline void destroy_node(xml_node_struct* n, xml_allocator& alloc)
  437. {
  438. uintptr_t header = n->header;
  439. if (header & impl::xml_memory_page_name_allocated_mask) alloc.deallocate_string(n->name);
  440. if (header & impl::xml_memory_page_value_allocated_mask) alloc.deallocate_string(n->value);
  441. for (xml_attribute_struct* attr = n->first_attribute; attr; )
  442. {
  443. xml_attribute_struct* next = attr->next_attribute;
  444. destroy_attribute(attr, alloc);
  445. attr = next;
  446. }
  447. for (xml_node_struct* child = n->first_child; child; )
  448. {
  449. xml_node_struct* next = child->next_sibling;
  450. destroy_node(child, alloc);
  451. child = next;
  452. }
  453. alloc.deallocate_memory(n, sizeof(xml_node_struct), reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask));
  454. }
  455. PUGI__FN_NO_INLINE xml_node_struct* append_node(xml_node_struct* node, xml_allocator& alloc, xml_node_type type = node_element)
  456. {
  457. xml_node_struct* child = allocate_node(alloc, type);
  458. if (!child) return 0;
  459. child->parent = node;
  460. xml_node_struct* first_child = node->first_child;
  461. if (first_child)
  462. {
  463. xml_node_struct* last_child = first_child->prev_sibling_c;
  464. last_child->next_sibling = child;
  465. child->prev_sibling_c = last_child;
  466. first_child->prev_sibling_c = child;
  467. }
  468. else
  469. {
  470. node->first_child = child;
  471. child->prev_sibling_c = child;
  472. }
  473. return child;
  474. }
  475. PUGI__FN_NO_INLINE xml_attribute_struct* append_attribute_ll(xml_node_struct* node, xml_allocator& alloc)
  476. {
  477. xml_attribute_struct* a = allocate_attribute(alloc);
  478. if (!a) return 0;
  479. xml_attribute_struct* first_attribute = node->first_attribute;
  480. if (first_attribute)
  481. {
  482. xml_attribute_struct* last_attribute = first_attribute->prev_attribute_c;
  483. last_attribute->next_attribute = a;
  484. a->prev_attribute_c = last_attribute;
  485. first_attribute->prev_attribute_c = a;
  486. }
  487. else
  488. {
  489. node->first_attribute = a;
  490. a->prev_attribute_c = a;
  491. }
  492. return a;
  493. }
  494. PUGI__NS_END
  495. // Helper classes for code generation
  496. PUGI__NS_BEGIN
  497. struct opt_false
  498. {
  499. enum { value = 0 };
  500. };
  501. struct opt_true
  502. {
  503. enum { value = 1 };
  504. };
  505. PUGI__NS_END
  506. // Unicode utilities
  507. PUGI__NS_BEGIN
  508. inline uint16_t endian_swap(uint16_t value)
  509. {
  510. return static_cast<uint16_t>(((value & 0xff) << 8) | (value >> 8));
  511. }
  512. inline uint32_t endian_swap(uint32_t value)
  513. {
  514. return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (value >> 24);
  515. }
  516. struct utf8_counter
  517. {
  518. typedef size_t value_type;
  519. static value_type low(value_type result, uint32_t ch)
  520. {
  521. // U+0000..U+007F
  522. if (ch < 0x80) return result + 1;
  523. // U+0080..U+07FF
  524. else if (ch < 0x800) return result + 2;
  525. // U+0800..U+FFFF
  526. else return result + 3;
  527. }
  528. static value_type high(value_type result, uint32_t)
  529. {
  530. // U+10000..U+10FFFF
  531. return result + 4;
  532. }
  533. };
  534. struct utf8_writer
  535. {
  536. typedef uint8_t* value_type;
  537. static value_type low(value_type result, uint32_t ch)
  538. {
  539. // U+0000..U+007F
  540. if (ch < 0x80)
  541. {
  542. *result = static_cast<uint8_t>(ch);
  543. return result + 1;
  544. }
  545. // U+0080..U+07FF
  546. else if (ch < 0x800)
  547. {
  548. result[0] = static_cast<uint8_t>(0xC0 | (ch >> 6));
  549. result[1] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  550. return result + 2;
  551. }
  552. // U+0800..U+FFFF
  553. else
  554. {
  555. result[0] = static_cast<uint8_t>(0xE0 | (ch >> 12));
  556. result[1] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
  557. result[2] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  558. return result + 3;
  559. }
  560. }
  561. static value_type high(value_type result, uint32_t ch)
  562. {
  563. // U+10000..U+10FFFF
  564. result[0] = static_cast<uint8_t>(0xF0 | (ch >> 18));
  565. result[1] = static_cast<uint8_t>(0x80 | ((ch >> 12) & 0x3F));
  566. result[2] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
  567. result[3] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  568. return result + 4;
  569. }
  570. static value_type any(value_type result, uint32_t ch)
  571. {
  572. return (ch < 0x10000) ? low(result, ch) : high(result, ch);
  573. }
  574. };
  575. struct utf16_counter
  576. {
  577. typedef size_t value_type;
  578. static value_type low(value_type result, uint32_t)
  579. {
  580. return result + 1;
  581. }
  582. static value_type high(value_type result, uint32_t)
  583. {
  584. return result + 2;
  585. }
  586. };
  587. struct utf16_writer
  588. {
  589. typedef uint16_t* value_type;
  590. static value_type low(value_type result, uint32_t ch)
  591. {
  592. *result = static_cast<uint16_t>(ch);
  593. return result + 1;
  594. }
  595. static value_type high(value_type result, uint32_t ch)
  596. {
  597. uint32_t msh = static_cast<uint32_t>(ch - 0x10000) >> 10;
  598. uint32_t lsh = static_cast<uint32_t>(ch - 0x10000) & 0x3ff;
  599. result[0] = static_cast<uint16_t>(0xD800 + msh);
  600. result[1] = static_cast<uint16_t>(0xDC00 + lsh);
  601. return result + 2;
  602. }
  603. static value_type any(value_type result, uint32_t ch)
  604. {
  605. return (ch < 0x10000) ? low(result, ch) : high(result, ch);
  606. }
  607. };
  608. struct utf32_counter
  609. {
  610. typedef size_t value_type;
  611. static value_type low(value_type result, uint32_t)
  612. {
  613. return result + 1;
  614. }
  615. static value_type high(value_type result, uint32_t)
  616. {
  617. return result + 1;
  618. }
  619. };
  620. struct utf32_writer
  621. {
  622. typedef uint32_t* value_type;
  623. static value_type low(value_type result, uint32_t ch)
  624. {
  625. *result = ch;
  626. return result + 1;
  627. }
  628. static value_type high(value_type result, uint32_t ch)
  629. {
  630. *result = ch;
  631. return result + 1;
  632. }
  633. static value_type any(value_type result, uint32_t ch)
  634. {
  635. *result = ch;
  636. return result + 1;
  637. }
  638. };
  639. struct latin1_writer
  640. {
  641. typedef uint8_t* value_type;
  642. static value_type low(value_type result, uint32_t ch)
  643. {
  644. *result = static_cast<uint8_t>(ch > 255 ? '?' : ch);
  645. return result + 1;
  646. }
  647. static value_type high(value_type result, uint32_t ch)
  648. {
  649. (void)ch;
  650. *result = '?';
  651. return result + 1;
  652. }
  653. };
  654. template <size_t size> struct wchar_selector;
  655. template <> struct wchar_selector<2>
  656. {
  657. typedef uint16_t type;
  658. typedef utf16_counter counter;
  659. typedef utf16_writer writer;
  660. };
  661. template <> struct wchar_selector<4>
  662. {
  663. typedef uint32_t type;
  664. typedef utf32_counter counter;
  665. typedef utf32_writer writer;
  666. };
  667. typedef wchar_selector<sizeof(wchar_t)>::counter wchar_counter;
  668. typedef wchar_selector<sizeof(wchar_t)>::writer wchar_writer;
  669. template <typename Traits, typename opt_swap = opt_false> struct utf_decoder
  670. {
  671. static inline typename Traits::value_type decode_utf8_block(const uint8_t* data, size_t size, typename Traits::value_type result)
  672. {
  673. const uint8_t utf8_byte_mask = 0x3f;
  674. while (size)
  675. {
  676. uint8_t lead = *data;
  677. // 0xxxxxxx -> U+0000..U+007F
  678. if (lead < 0x80)
  679. {
  680. result = Traits::low(result, lead);
  681. data += 1;
  682. size -= 1;
  683. // process aligned single-byte (ascii) blocks
  684. if ((reinterpret_cast<uintptr_t>(data) & 3) == 0)
  685. {
  686. // round-trip through void* to silence 'cast increases required alignment of target type' warnings
  687. while (size >= 4 && (*static_cast<const uint32_t*>(static_cast<const void*>(data)) & 0x80808080) == 0)
  688. {
  689. result = Traits::low(result, data[0]);
  690. result = Traits::low(result, data[1]);
  691. result = Traits::low(result, data[2]);
  692. result = Traits::low(result, data[3]);
  693. data += 4;
  694. size -= 4;
  695. }
  696. }
  697. }
  698. // 110xxxxx -> U+0080..U+07FF
  699. else if (static_cast<unsigned int>(lead - 0xC0) < 0x20 && size >= 2 && (data[1] & 0xc0) == 0x80)
  700. {
  701. result = Traits::low(result, ((lead & ~0xC0) << 6) | (data[1] & utf8_byte_mask));
  702. data += 2;
  703. size -= 2;
  704. }
  705. // 1110xxxx -> U+0800-U+FFFF
  706. else if (static_cast<unsigned int>(lead - 0xE0) < 0x10 && size >= 3 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80)
  707. {
  708. result = Traits::low(result, ((lead & ~0xE0) << 12) | ((data[1] & utf8_byte_mask) << 6) | (data[2] & utf8_byte_mask));
  709. data += 3;
  710. size -= 3;
  711. }
  712. // 11110xxx -> U+10000..U+10FFFF
  713. else if (static_cast<unsigned int>(lead - 0xF0) < 0x08 && size >= 4 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80 && (data[3] & 0xc0) == 0x80)
  714. {
  715. result = Traits::high(result, ((lead & ~0xF0) << 18) | ((data[1] & utf8_byte_mask) << 12) | ((data[2] & utf8_byte_mask) << 6) | (data[3] & utf8_byte_mask));
  716. data += 4;
  717. size -= 4;
  718. }
  719. // 10xxxxxx or 11111xxx -> invalid
  720. else
  721. {
  722. data += 1;
  723. size -= 1;
  724. }
  725. }
  726. return result;
  727. }
  728. static inline typename Traits::value_type decode_utf16_block(const uint16_t* data, size_t size, typename Traits::value_type result)
  729. {
  730. const uint16_t* end = data + size;
  731. while (data < end)
  732. {
  733. uint16_t lead = opt_swap::value ? endian_swap(*data) : *data;
  734. // U+0000..U+D7FF
  735. if (lead < 0xD800)
  736. {
  737. result = Traits::low(result, lead);
  738. data += 1;
  739. }
  740. // U+E000..U+FFFF
  741. else if (static_cast<unsigned int>(lead - 0xE000) < 0x2000)
  742. {
  743. result = Traits::low(result, lead);
  744. data += 1;
  745. }
  746. // surrogate pair lead
  747. else if (static_cast<unsigned int>(lead - 0xD800) < 0x400 && data + 1 < end)
  748. {
  749. uint16_t next = opt_swap::value ? endian_swap(data[1]) : data[1];
  750. if (static_cast<unsigned int>(next - 0xDC00) < 0x400)
  751. {
  752. result = Traits::high(result, 0x10000 + ((lead & 0x3ff) << 10) + (next & 0x3ff));
  753. data += 2;
  754. }
  755. else
  756. {
  757. data += 1;
  758. }
  759. }
  760. else
  761. {
  762. data += 1;
  763. }
  764. }
  765. return result;
  766. }
  767. static inline typename Traits::value_type decode_utf32_block(const uint32_t* data, size_t size, typename Traits::value_type result)
  768. {
  769. const uint32_t* end = data + size;
  770. while (data < end)
  771. {
  772. uint32_t lead = opt_swap::value ? endian_swap(*data) : *data;
  773. // U+0000..U+FFFF
  774. if (lead < 0x10000)
  775. {
  776. result = Traits::low(result, lead);
  777. data += 1;
  778. }
  779. // U+10000..U+10FFFF
  780. else
  781. {
  782. result = Traits::high(result, lead);
  783. data += 1;
  784. }
  785. }
  786. return result;
  787. }
  788. static inline typename Traits::value_type decode_latin1_block(const uint8_t* data, size_t size, typename Traits::value_type result)
  789. {
  790. for (size_t i = 0; i < size; ++i)
  791. {
  792. result = Traits::low(result, data[i]);
  793. }
  794. return result;
  795. }
  796. static inline typename Traits::value_type decode_wchar_block_impl(const uint16_t* data, size_t size, typename Traits::value_type result)
  797. {
  798. return decode_utf16_block(data, size, result);
  799. }
  800. static inline typename Traits::value_type decode_wchar_block_impl(const uint32_t* data, size_t size, typename Traits::value_type result)
  801. {
  802. return decode_utf32_block(data, size, result);
  803. }
  804. static inline typename Traits::value_type decode_wchar_block(const wchar_t* data, size_t size, typename Traits::value_type result)
  805. {
  806. return decode_wchar_block_impl(reinterpret_cast<const wchar_selector<sizeof(wchar_t)>::type*>(data), size, result);
  807. }
  808. };
  809. template <typename T> PUGI__FN void convert_utf_endian_swap(T* result, const T* data, size_t length)
  810. {
  811. for (size_t i = 0; i < length; ++i) result[i] = endian_swap(data[i]);
  812. }
  813. #ifdef PUGIXML_WCHAR_MODE
  814. PUGI__FN void convert_wchar_endian_swap(wchar_t* result, const wchar_t* data, size_t length)
  815. {
  816. for (size_t i = 0; i < length; ++i) result[i] = static_cast<wchar_t>(endian_swap(static_cast<wchar_selector<sizeof(wchar_t)>::type>(data[i])));
  817. }
  818. #endif
  819. PUGI__NS_END
  820. PUGI__NS_BEGIN
  821. enum chartype_t
  822. {
  823. ct_parse_pcdata = 1, // \0, &, \r, <
  824. ct_parse_attr = 2, // \0, &, \r, ', "
  825. ct_parse_attr_ws = 4, // \0, &, \r, ', ", \n, tab
  826. ct_space = 8, // \r, \n, space, tab
  827. ct_parse_cdata = 16, // \0, ], >, \r
  828. ct_parse_comment = 32, // \0, -, >, \r
  829. ct_symbol = 64, // Any symbol > 127, a-z, A-Z, 0-9, _, :, -, .
  830. ct_start_symbol = 128 // Any symbol > 127, a-z, A-Z, _, :
  831. };
  832. static const unsigned char chartype_table[256] =
  833. {
  834. 55, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 0, 0, 63, 0, 0, // 0-15
  835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
  836. 8, 0, 6, 0, 0, 0, 7, 6, 0, 0, 0, 0, 0, 96, 64, 0, // 32-47
  837. 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 192, 0, 1, 0, 48, 0, // 48-63
  838. 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 64-79
  839. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 16, 0, 192, // 80-95
  840. 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 96-111
  841. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 0, // 112-127
  842. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 128+
  843. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  844. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  845. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  846. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  847. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  848. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  849. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192
  850. };
  851. enum chartypex_t
  852. {
  853. ctx_special_pcdata = 1, // Any symbol >= 0 and < 32 (except \t, \r, \n), &, <, >
  854. ctx_special_attr = 2, // Any symbol >= 0 and < 32 (except \t), &, <, >, "
  855. ctx_start_symbol = 4, // Any symbol > 127, a-z, A-Z, _
  856. ctx_digit = 8, // 0-9
  857. ctx_symbol = 16 // Any symbol > 127, a-z, A-Z, 0-9, _, -, .
  858. };
  859. static const unsigned char chartypex_table[256] =
  860. {
  861. 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 2, 3, 3, 2, 3, 3, // 0-15
  862. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 16-31
  863. 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 16, 16, 0, // 32-47
  864. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 3, 0, 3, 0, // 48-63
  865. 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 64-79
  866. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 20, // 80-95
  867. 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 96-111
  868. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, // 112-127
  869. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 128+
  870. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  871. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  872. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  873. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  874. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  875. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  876. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20
  877. };
  878. #ifdef PUGIXML_WCHAR_MODE
  879. #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) ((static_cast<unsigned int>(c) < 128 ? table[static_cast<unsigned int>(c)] : table[128]) & (ct))
  880. #else
  881. #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) (table[static_cast<unsigned char>(c)] & (ct))
  882. #endif
  883. #define PUGI__IS_CHARTYPE(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartype_table)
  884. #define PUGI__IS_CHARTYPEX(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartypex_table)
  885. PUGI__FN bool is_little_endian()
  886. {
  887. unsigned int ui = 1;
  888. return *reinterpret_cast<unsigned char*>(&ui) == 1;
  889. }
  890. PUGI__FN xml_encoding get_wchar_encoding()
  891. {
  892. PUGI__STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4);
  893. if (sizeof(wchar_t) == 2)
  894. return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  895. else
  896. return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  897. }
  898. PUGI__FN xml_encoding guess_buffer_encoding(uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)
  899. {
  900. // look for BOM in first few bytes
  901. if (d0 == 0 && d1 == 0 && d2 == 0xfe && d3 == 0xff) return encoding_utf32_be;
  902. if (d0 == 0xff && d1 == 0xfe && d2 == 0 && d3 == 0) return encoding_utf32_le;
  903. if (d0 == 0xfe && d1 == 0xff) return encoding_utf16_be;
  904. if (d0 == 0xff && d1 == 0xfe) return encoding_utf16_le;
  905. if (d0 == 0xef && d1 == 0xbb && d2 == 0xbf) return encoding_utf8;
  906. // look for <, <? or <?xm in various encodings
  907. if (d0 == 0 && d1 == 0 && d2 == 0 && d3 == 0x3c) return encoding_utf32_be;
  908. if (d0 == 0x3c && d1 == 0 && d2 == 0 && d3 == 0) return encoding_utf32_le;
  909. if (d0 == 0 && d1 == 0x3c && d2 == 0 && d3 == 0x3f) return encoding_utf16_be;
  910. if (d0 == 0x3c && d1 == 0 && d2 == 0x3f && d3 == 0) return encoding_utf16_le;
  911. if (d0 == 0x3c && d1 == 0x3f && d2 == 0x78 && d3 == 0x6d) return encoding_utf8;
  912. // look for utf16 < followed by node name (this may fail, but is better than utf8 since it's zero terminated so early)
  913. if (d0 == 0 && d1 == 0x3c) return encoding_utf16_be;
  914. if (d0 == 0x3c && d1 == 0) return encoding_utf16_le;
  915. // no known BOM detected, assume utf8
  916. return encoding_utf8;
  917. }
  918. PUGI__FN xml_encoding get_buffer_encoding(xml_encoding encoding, const void* contents, size_t size)
  919. {
  920. // replace wchar encoding with utf implementation
  921. if (encoding == encoding_wchar) return get_wchar_encoding();
  922. // replace utf16 encoding with utf16 with specific endianness
  923. if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  924. // replace utf32 encoding with utf32 with specific endianness
  925. if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  926. // only do autodetection if no explicit encoding is requested
  927. if (encoding != encoding_auto) return encoding;
  928. // skip encoding autodetection if input buffer is too small
  929. if (size < 4) return encoding_utf8;
  930. // try to guess encoding (based on XML specification, Appendix F.1)
  931. const uint8_t* data = static_cast<const uint8_t*>(contents);
  932. PUGI__DMC_VOLATILE uint8_t d0 = data[0], d1 = data[1], d2 = data[2], d3 = data[3];
  933. return guess_buffer_encoding(d0, d1, d2, d3);
  934. }
  935. PUGI__FN bool get_mutable_buffer(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  936. {
  937. if (is_mutable)
  938. {
  939. out_buffer = static_cast<char_t*>(const_cast<void*>(contents));
  940. }
  941. else
  942. {
  943. void* buffer = xml_memory::allocate(size > 0 ? size : 1);
  944. if (!buffer) return false;
  945. memcpy(buffer, contents, size);
  946. out_buffer = static_cast<char_t*>(buffer);
  947. }
  948. out_length = size / sizeof(char_t);
  949. return true;
  950. }
  951. #ifdef PUGIXML_WCHAR_MODE
  952. PUGI__FN bool need_endian_swap_utf(xml_encoding le, xml_encoding re)
  953. {
  954. return (le == encoding_utf16_be && re == encoding_utf16_le) || (le == encoding_utf16_le && re == encoding_utf16_be) ||
  955. (le == encoding_utf32_be && re == encoding_utf32_le) || (le == encoding_utf32_le && re == encoding_utf32_be);
  956. }
  957. PUGI__FN bool convert_buffer_endian_swap(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  958. {
  959. const char_t* data = static_cast<const char_t*>(contents);
  960. if (is_mutable)
  961. {
  962. out_buffer = const_cast<char_t*>(data);
  963. }
  964. else
  965. {
  966. out_buffer = static_cast<char_t*>(xml_memory::allocate(size > 0 ? size : 1));
  967. if (!out_buffer) return false;
  968. }
  969. out_length = size / sizeof(char_t);
  970. convert_wchar_endian_swap(out_buffer, data, out_length);
  971. return true;
  972. }
  973. PUGI__FN bool convert_buffer_utf8(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size)
  974. {
  975. const uint8_t* data = static_cast<const uint8_t*>(contents);
  976. // first pass: get length in wchar_t units
  977. out_length = utf_decoder<wchar_counter>::decode_utf8_block(data, size, 0);
  978. // allocate buffer of suitable length
  979. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  980. if (!out_buffer) return false;
  981. // second pass: convert utf8 input to wchar_t
  982. wchar_writer::value_type out_begin = reinterpret_cast<wchar_writer::value_type>(out_buffer);
  983. wchar_writer::value_type out_end = utf_decoder<wchar_writer>::decode_utf8_block(data, size, out_begin);
  984. assert(out_end == out_begin + out_length);
  985. (void)!out_end;
  986. return true;
  987. }
  988. template <typename opt_swap> PUGI__FN bool convert_buffer_utf16(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  989. {
  990. const uint16_t* data = static_cast<const uint16_t*>(contents);
  991. size_t length = size / sizeof(uint16_t);
  992. // first pass: get length in wchar_t units
  993. out_length = utf_decoder<wchar_counter, opt_swap>::decode_utf16_block(data, length, 0);
  994. // allocate buffer of suitable length
  995. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  996. if (!out_buffer) return false;
  997. // second pass: convert utf16 input to wchar_t
  998. wchar_writer::value_type out_begin = reinterpret_cast<wchar_writer::value_type>(out_buffer);
  999. wchar_writer::value_type out_end = utf_decoder<wchar_writer, opt_swap>::decode_utf16_block(data, length, out_begin);
  1000. assert(out_end == out_begin + out_length);
  1001. (void)!out_end;
  1002. return true;
  1003. }
  1004. template <typename opt_swap> PUGI__FN bool convert_buffer_utf32(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1005. {
  1006. const uint32_t* data = static_cast<const uint32_t*>(contents);
  1007. size_t length = size / sizeof(uint32_t);
  1008. // first pass: get length in wchar_t units
  1009. out_length = utf_decoder<wchar_counter, opt_swap>::decode_utf32_block(data, length, 0);
  1010. // allocate buffer of suitable length
  1011. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  1012. if (!out_buffer) return false;
  1013. // second pass: convert utf32 input to wchar_t
  1014. wchar_writer::value_type out_begin = reinterpret_cast<wchar_writer::value_type>(out_buffer);
  1015. wchar_writer::value_type out_end = utf_decoder<wchar_writer, opt_swap>::decode_utf32_block(data, length, out_begin);
  1016. assert(out_end == out_begin + out_length);
  1017. (void)!out_end;
  1018. return true;
  1019. }
  1020. PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size)
  1021. {
  1022. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1023. // get length in wchar_t units
  1024. out_length = size;
  1025. // allocate buffer of suitable length
  1026. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  1027. if (!out_buffer) return false;
  1028. // convert latin1 input to wchar_t
  1029. wchar_writer::value_type out_begin = reinterpret_cast<wchar_writer::value_type>(out_buffer);
  1030. wchar_writer::value_type out_end = utf_decoder<wchar_writer>::decode_latin1_block(data, size, out_begin);
  1031. assert(out_end == out_begin + out_length);
  1032. (void)!out_end;
  1033. return true;
  1034. }
  1035. PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)
  1036. {
  1037. // get native encoding
  1038. xml_encoding wchar_encoding = get_wchar_encoding();
  1039. // fast path: no conversion required
  1040. if (encoding == wchar_encoding) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1041. // only endian-swapping is required
  1042. if (need_endian_swap_utf(encoding, wchar_encoding)) return convert_buffer_endian_swap(out_buffer, out_length, contents, size, is_mutable);
  1043. // source encoding is utf8
  1044. if (encoding == encoding_utf8) return convert_buffer_utf8(out_buffer, out_length, contents, size);
  1045. // source encoding is utf16
  1046. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  1047. {
  1048. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1049. return (native_encoding == encoding) ?
  1050. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_false()) :
  1051. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_true());
  1052. }
  1053. // source encoding is utf32
  1054. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  1055. {
  1056. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1057. return (native_encoding == encoding) ?
  1058. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_false()) :
  1059. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_true());
  1060. }
  1061. // source encoding is latin1
  1062. if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size);
  1063. assert(!"Invalid encoding");
  1064. return false;
  1065. }
  1066. #else
  1067. template <typename opt_swap> PUGI__FN bool convert_buffer_utf16(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1068. {
  1069. const uint16_t* data = static_cast<const uint16_t*>(contents);
  1070. size_t length = size / sizeof(uint16_t);
  1071. // first pass: get length in utf8 units
  1072. out_length = utf_decoder<utf8_counter, opt_swap>::decode_utf16_block(data, length, 0);
  1073. // allocate buffer of suitable length
  1074. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  1075. if (!out_buffer) return false;
  1076. // second pass: convert utf16 input to utf8
  1077. uint8_t* out_begin = reinterpret_cast<uint8_t*>(out_buffer);
  1078. uint8_t* out_end = utf_decoder<utf8_writer, opt_swap>::decode_utf16_block(data, length, out_begin);
  1079. assert(out_end == out_begin + out_length);
  1080. (void)!out_end;
  1081. return true;
  1082. }
  1083. template <typename opt_swap> PUGI__FN bool convert_buffer_utf32(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, opt_swap)
  1084. {
  1085. const uint32_t* data = static_cast<const uint32_t*>(contents);
  1086. size_t length = size / sizeof(uint32_t);
  1087. // first pass: get length in utf8 units
  1088. out_length = utf_decoder<utf8_counter, opt_swap>::decode_utf32_block(data, length, 0);
  1089. // allocate buffer of suitable length
  1090. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  1091. if (!out_buffer) return false;
  1092. // second pass: convert utf32 input to utf8
  1093. uint8_t* out_begin = reinterpret_cast<uint8_t*>(out_buffer);
  1094. uint8_t* out_end = utf_decoder<utf8_writer, opt_swap>::decode_utf32_block(data, length, out_begin);
  1095. assert(out_end == out_begin + out_length);
  1096. (void)!out_end;
  1097. return true;
  1098. }
  1099. PUGI__FN size_t get_latin1_7bit_prefix_length(const uint8_t* data, size_t size)
  1100. {
  1101. for (size_t i = 0; i < size; ++i)
  1102. if (data[i] > 127)
  1103. return i;
  1104. return size;
  1105. }
  1106. PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1107. {
  1108. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1109. // get size of prefix that does not need utf8 conversion
  1110. size_t prefix_length = get_latin1_7bit_prefix_length(data, size);
  1111. assert(prefix_length <= size);
  1112. const uint8_t* postfix = data + prefix_length;
  1113. size_t postfix_length = size - prefix_length;
  1114. // if no conversion is needed, just return the original buffer
  1115. if (postfix_length == 0) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1116. // first pass: get length in utf8 units
  1117. out_length = prefix_length + utf_decoder<utf8_counter>::decode_latin1_block(postfix, postfix_length, 0);
  1118. // allocate buffer of suitable length
  1119. out_buffer = static_cast<char_t*>(xml_memory::allocate((out_length > 0 ? out_length : 1) * sizeof(char_t)));
  1120. if (!out_buffer) return false;
  1121. // second pass: convert latin1 input to utf8
  1122. memcpy(out_buffer, data, prefix_length);
  1123. uint8_t* out_begin = reinterpret_cast<uint8_t*>(out_buffer);
  1124. uint8_t* out_end = utf_decoder<utf8_writer>::decode_latin1_block(postfix, postfix_length, out_begin + prefix_length);
  1125. assert(out_end == out_begin + out_length);
  1126. (void)!out_end;
  1127. return true;
  1128. }
  1129. PUGI__FN bool convert_buffer(char_t*& out_buffer, size_t& out_length, xml_encoding encoding, const void* contents, size_t size, bool is_mutable)
  1130. {
  1131. // fast path: no conversion required
  1132. if (encoding == encoding_utf8) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1133. // source encoding is utf16
  1134. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  1135. {
  1136. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1137. return (native_encoding == encoding) ?
  1138. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_false()) :
  1139. convert_buffer_utf16(out_buffer, out_length, contents, size, opt_true());
  1140. }
  1141. // source encoding is utf32
  1142. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  1143. {
  1144. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1145. return (native_encoding == encoding) ?
  1146. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_false()) :
  1147. convert_buffer_utf32(out_buffer, out_length, contents, size, opt_true());
  1148. }
  1149. // source encoding is latin1
  1150. if (encoding == encoding_latin1) return convert_buffer_latin1(out_buffer, out_length, contents, size, is_mutable);
  1151. assert(!"Invalid encoding");
  1152. return false;
  1153. }
  1154. #endif
  1155. PUGI__FN size_t as_utf8_begin(const wchar_t* str, size_t length)
  1156. {
  1157. // get length in utf8 characters
  1158. return utf_decoder<utf8_counter>::decode_wchar_block(str, length, 0);
  1159. }
  1160. PUGI__FN void as_utf8_end(char* buffer, size_t size, const wchar_t* str, size_t length)
  1161. {
  1162. // convert to utf8
  1163. uint8_t* begin = reinterpret_cast<uint8_t*>(buffer);
  1164. uint8_t* end = utf_decoder<utf8_writer>::decode_wchar_block(str, length, begin);
  1165. assert(begin + size == end);
  1166. (void)!end;
  1167. // zero-terminate
  1168. buffer[size] = 0;
  1169. }
  1170. #ifndef PUGIXML_NO_STL
  1171. PUGI__FN std::string as_utf8_impl(const wchar_t* str, size_t length)
  1172. {
  1173. // first pass: get length in utf8 characters
  1174. size_t size = as_utf8_begin(str, length);
  1175. // allocate resulting string
  1176. std::string result;
  1177. result.resize(size);
  1178. // second pass: convert to utf8
  1179. if (size > 0) as_utf8_end(&result[0], size, str, length);
  1180. return result;
  1181. }
  1182. PUGI__FN std::basic_string<wchar_t> as_wide_impl(const char* str, size_t size)
  1183. {
  1184. const uint8_t* data = reinterpret_cast<const uint8_t*>(str);
  1185. // first pass: get length in wchar_t units
  1186. size_t length = utf_decoder<wchar_counter>::decode_utf8_block(data, size, 0);
  1187. // allocate resulting string
  1188. std::basic_string<wchar_t> result;
  1189. result.resize(length);
  1190. // second pass: convert to wchar_t
  1191. if (length > 0)
  1192. {
  1193. wchar_writer::value_type begin = reinterpret_cast<wchar_writer::value_type>(&result[0]);
  1194. wchar_writer::value_type end = utf_decoder<wchar_writer>::decode_utf8_block(data, size, begin);
  1195. assert(begin + length == end);
  1196. (void)!end;
  1197. }
  1198. return result;
  1199. }
  1200. #endif
  1201. inline bool strcpy_insitu_allow(size_t length, uintptr_t allocated, char_t* target)
  1202. {
  1203. assert(target);
  1204. size_t target_length = strlength(target);
  1205. // always reuse document buffer memory if possible
  1206. if (!allocated) return target_length >= length;
  1207. // reuse heap memory if waste is not too great
  1208. const size_t reuse_threshold = 32;
  1209. return target_length >= length && (target_length < reuse_threshold || target_length - length < target_length / 2);
  1210. }
  1211. PUGI__FN bool strcpy_insitu(char_t*& dest, uintptr_t& header, uintptr_t header_mask, const char_t* source)
  1212. {
  1213. size_t source_length = strlength(source);
  1214. if (source_length == 0)
  1215. {
  1216. // empty string and null pointer are equivalent, so just deallocate old memory
  1217. xml_allocator* alloc = reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask)->allocator;
  1218. if (header & header_mask) alloc->deallocate_string(dest);
  1219. // mark the string as not allocated
  1220. dest = 0;
  1221. header &= ~header_mask;
  1222. return true;
  1223. }
  1224. else if (dest && strcpy_insitu_allow(source_length, header & header_mask, dest))
  1225. {
  1226. // we can reuse old buffer, so just copy the new data (including zero terminator)
  1227. memcpy(dest, source, (source_length + 1) * sizeof(char_t));
  1228. return true;
  1229. }
  1230. else
  1231. {
  1232. xml_allocator* alloc = reinterpret_cast<xml_memory_page*>(header & xml_memory_page_pointer_mask)->allocator;
  1233. // allocate new buffer
  1234. char_t* buf = alloc->allocate_string(source_length + 1);
  1235. if (!buf) return false;
  1236. // copy the string (including zero terminator)
  1237. memcpy(buf, source, (source_length + 1) * sizeof(char_t));
  1238. // deallocate old buffer (*after* the above to protect against overlapping memory and/or allocation failures)
  1239. if (header & header_mask) alloc->deallocate_string(dest);
  1240. // the string is now allocated, so set the flag
  1241. dest = buf;
  1242. header |= header_mask;
  1243. return true;
  1244. }
  1245. }
  1246. struct gap
  1247. {
  1248. char_t* end;
  1249. size_t size;
  1250. gap(): end(0), size(0)
  1251. {
  1252. }
  1253. // Push new gap, move s count bytes further (skipping the gap).
  1254. // Collapse previous gap.
  1255. void push(char_t*& s, size_t count)
  1256. {
  1257. if (end) // there was a gap already; collapse it
  1258. {
  1259. // Move [old_gap_end, new_gap_start) to [old_gap_start, ...)
  1260. assert(s >= end);
  1261. memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
  1262. }
  1263. s += count; // end of current gap
  1264. // "merge" two gaps
  1265. end = s;
  1266. size += count;
  1267. }
  1268. // Collapse all gaps, return past-the-end pointer
  1269. char_t* flush(char_t* s)
  1270. {
  1271. if (end)
  1272. {
  1273. // Move [old_gap_end, current_pos) to [old_gap_start, ...)
  1274. assert(s >= end);
  1275. memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
  1276. return s - size;
  1277. }
  1278. else return s;
  1279. }
  1280. };
  1281. PUGI__FN char_t* strconv_escape(char_t* s, gap& g)
  1282. {
  1283. char_t* stre = s + 1;
  1284. switch (*stre)
  1285. {
  1286. case '#': // &#...
  1287. {
  1288. unsigned int ucsc = 0;
  1289. if (stre[1] == 'x') // &#x... (hex code)
  1290. {
  1291. stre += 2;
  1292. char_t ch = *stre;
  1293. if (ch == ';') return stre;
  1294. for (;;)
  1295. {
  1296. if (static_cast<unsigned int>(ch - '0') <= 9)
  1297. ucsc = 16 * ucsc + (ch - '0');
  1298. else if (static_cast<unsigned int>((ch | ' ') - 'a') <= 5)
  1299. ucsc = 16 * ucsc + ((ch | ' ') - 'a' + 10);
  1300. else if (ch == ';')
  1301. break;
  1302. else // cancel
  1303. return stre;
  1304. ch = *++stre;
  1305. }
  1306. ++stre;
  1307. }
  1308. else // &#... (dec code)
  1309. {
  1310. char_t ch = *++stre;
  1311. if (ch == ';') return stre;
  1312. for (;;)
  1313. {
  1314. if (static_cast<unsigned int>(ch - '0') <= 9)
  1315. ucsc = 10 * ucsc + (ch - '0');
  1316. else if (ch == ';')
  1317. break;
  1318. else // cancel
  1319. return stre;
  1320. ch = *++stre;
  1321. }
  1322. ++stre;
  1323. }
  1324. #ifdef PUGIXML_WCHAR_MODE
  1325. s = reinterpret_cast<char_t*>(wchar_writer::any(reinterpret_cast<wchar_writer::value_type>(s), ucsc));
  1326. #else
  1327. s = reinterpret_cast<char_t*>(utf8_writer::any(reinterpret_cast<uint8_t*>(s), ucsc));
  1328. #endif
  1329. g.push(s, stre - s);
  1330. return stre;
  1331. }
  1332. case 'a': // &a
  1333. {
  1334. ++stre;
  1335. if (*stre == 'm') // &am
  1336. {
  1337. if (*++stre == 'p' && *++stre == ';') // &amp;
  1338. {
  1339. *s++ = '&';
  1340. ++stre;
  1341. g.push(s, stre - s);
  1342. return stre;
  1343. }
  1344. }
  1345. else if (*stre == 'p') // &ap
  1346. {
  1347. if (*++stre == 'o' && *++stre == 's' && *++stre == ';') // &apos;
  1348. {
  1349. *s++ = '\'';
  1350. ++stre;
  1351. g.push(s, stre - s);
  1352. return stre;
  1353. }
  1354. }
  1355. break;
  1356. }
  1357. case 'g': // &g
  1358. {
  1359. if (*++stre == 't' && *++stre == ';') // &gt;
  1360. {
  1361. *s++ = '>';
  1362. ++stre;
  1363. g.push(s, stre - s);
  1364. return stre;
  1365. }
  1366. break;
  1367. }
  1368. case 'l': // &l
  1369. {
  1370. if (*++stre == 't' && *++stre == ';') // &lt;
  1371. {
  1372. *s++ = '<';
  1373. ++stre;
  1374. g.push(s, stre - s);
  1375. return stre;
  1376. }
  1377. break;
  1378. }
  1379. case 'q': // &q
  1380. {
  1381. if (*++stre == 'u' && *++stre == 'o' && *++stre == 't' && *++stre == ';') // &quot;
  1382. {
  1383. *s++ = '"';
  1384. ++stre;
  1385. g.push(s, stre - s);
  1386. return stre;
  1387. }
  1388. break;
  1389. }
  1390. default:
  1391. break;
  1392. }
  1393. return stre;
  1394. }
  1395. // Utility macro for last character handling
  1396. #define ENDSWITH(c, e) ((c) == (e) || ((c) == 0 && endch == (e)))
  1397. PUGI__FN char_t* strconv_comment(char_t* s, char_t endch)
  1398. {
  1399. gap g;
  1400. while (true)
  1401. {
  1402. while (!PUGI__IS_CHARTYPE(*s, ct_parse_comment)) ++s;
  1403. if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  1404. {
  1405. *s++ = '\n'; // replace first one with 0x0a
  1406. if (*s == '\n') g.push(s, 1);
  1407. }
  1408. else if (s[0] == '-' && s[1] == '-' && ENDSWITH(s[2], '>')) // comment ends here
  1409. {
  1410. *g.flush(s) = 0;
  1411. return s + (s[2] == '>' ? 3 : 2);
  1412. }
  1413. else if (*s == 0)
  1414. {
  1415. return 0;
  1416. }
  1417. else ++s;
  1418. }
  1419. }
  1420. PUGI__FN char_t* strconv_cdata(char_t* s, char_t endch)
  1421. {
  1422. gap g;
  1423. while (true)
  1424. {
  1425. while (!PUGI__IS_CHARTYPE(*s, ct_parse_cdata)) ++s;
  1426. if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  1427. {
  1428. *s++ = '\n'; // replace first one with 0x0a
  1429. if (*s == '\n') g.push(s, 1);
  1430. }
  1431. else if (s[0] == ']' && s[1] == ']' && ENDSWITH(s[2], '>')) // CDATA ends here
  1432. {
  1433. *g.flush(s) = 0;
  1434. return s + 1;
  1435. }
  1436. else if (*s == 0)
  1437. {
  1438. return 0;
  1439. }
  1440. else ++s;
  1441. }
  1442. }
  1443. typedef char_t* (*strconv_pcdata_t)(char_t*);
  1444. template <typename opt_eol, typename opt_escape> struct strconv_pcdata_impl
  1445. {
  1446. static char_t* parse(char_t* s)
  1447. {
  1448. gap g;
  1449. while (true)
  1450. {
  1451. while (!PUGI__IS_CHARTYPE(*s, ct_parse_pcdata)) ++s;
  1452. if (*s == '<') // PCDATA ends here
  1453. {
  1454. *g.flush(s) = 0;
  1455. return s + 1;
  1456. }
  1457. else if (opt_eol::value && *s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  1458. {
  1459. *s++ = '\n'; // replace first one with 0x0a
  1460. if (*s == '\n') g.push(s, 1);
  1461. }
  1462. else if (opt_escape::value && *s == '&')
  1463. {
  1464. s = strconv_escape(s, g);
  1465. }
  1466. else if (*s == 0)
  1467. {
  1468. return s;
  1469. }
  1470. else ++s;
  1471. }
  1472. }
  1473. };
  1474. PUGI__FN strconv_pcdata_t get_strconv_pcdata(unsigned int optmask)
  1475. {
  1476. PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20);
  1477. switch ((optmask >> 4) & 3) // get bitmask for flags (eol escapes)
  1478. {
  1479. case 0: return strconv_pcdata_impl<opt_false, opt_false>::parse;
  1480. case 1: return strconv_pcdata_impl<opt_false, opt_true>::parse;
  1481. case 2: return strconv_pcdata_impl<opt_true, opt_false>::parse;
  1482. case 3: return strconv_pcdata_impl<opt_true, opt_true>::parse;
  1483. default: return 0; // should not get here
  1484. }
  1485. }
  1486. typedef char_t* (*strconv_attribute_t)(char_t*, char_t);
  1487. template <typename opt_escape> struct strconv_attribute_impl
  1488. {
  1489. static char_t* parse_wnorm(char_t* s, char_t end_quote)
  1490. {
  1491. gap g;
  1492. // trim leading whitespaces
  1493. if (PUGI__IS_CHARTYPE(*s, ct_space))
  1494. {
  1495. char_t* str = s;
  1496. do ++str;
  1497. while (PUGI__IS_CHARTYPE(*str, ct_space));
  1498. g.push(s, str - s);
  1499. }
  1500. while (true)
  1501. {
  1502. while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr_ws | ct_space)) ++s;
  1503. if (*s == end_quote)
  1504. {
  1505. char_t* str = g.flush(s);
  1506. do *str-- = 0;
  1507. while (PUGI__IS_CHARTYPE(*str, ct_space));
  1508. return s + 1;
  1509. }
  1510. else if (PUGI__IS_CHARTYPE(*s, ct_space))
  1511. {
  1512. *s++ = ' ';
  1513. if (PUGI__IS_CHARTYPE(*s, ct_space))
  1514. {
  1515. char_t* str = s + 1;
  1516. while (PUGI__IS_CHARTYPE(*str, ct_space)) ++str;
  1517. g.push(s, str - s);
  1518. }
  1519. }
  1520. else if (opt_escape::value && *s == '&')
  1521. {
  1522. s = strconv_escape(s, g);
  1523. }
  1524. else if (!*s)
  1525. {
  1526. return 0;
  1527. }
  1528. else ++s;
  1529. }
  1530. }
  1531. static char_t* parse_wconv(char_t* s, char_t end_quote)
  1532. {
  1533. gap g;
  1534. while (true)
  1535. {
  1536. while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr_ws)) ++s;
  1537. if (*s == end_quote)
  1538. {
  1539. *g.flush(s) = 0;
  1540. return s + 1;
  1541. }
  1542. else if (PUGI__IS_CHARTYPE(*s, ct_space))
  1543. {
  1544. if (*s == '\r')
  1545. {
  1546. *s++ = ' ';
  1547. if (*s == '\n') g.push(s, 1);
  1548. }
  1549. else *s++ = ' ';
  1550. }
  1551. else if (opt_escape::value && *s == '&')
  1552. {
  1553. s = strconv_escape(s, g);
  1554. }
  1555. else if (!*s)
  1556. {
  1557. return 0;
  1558. }
  1559. else ++s;
  1560. }
  1561. }
  1562. static char_t* parse_eol(char_t* s, char_t end_quote)
  1563. {
  1564. gap g;
  1565. while (true)
  1566. {
  1567. while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr)) ++s;
  1568. if (*s == end_quote)
  1569. {
  1570. *g.flush(s) = 0;
  1571. return s + 1;
  1572. }
  1573. else if (*s == '\r')
  1574. {
  1575. *s++ = '\n';
  1576. if (*s == '\n') g.push(s, 1);
  1577. }
  1578. else if (opt_escape::value && *s == '&')
  1579. {
  1580. s = strconv_escape(s, g);
  1581. }
  1582. else if (!*s)
  1583. {
  1584. return 0;
  1585. }
  1586. else ++s;
  1587. }
  1588. }
  1589. static char_t* parse_simple(char_t* s, char_t end_quote)
  1590. {
  1591. gap g;
  1592. while (true)
  1593. {
  1594. while (!PUGI__IS_CHARTYPE(*s, ct_parse_attr)) ++s;
  1595. if (*s == end_quote)
  1596. {
  1597. *g.flush(s) = 0;
  1598. return s + 1;
  1599. }
  1600. else if (opt_escape::value && *s == '&')
  1601. {
  1602. s = strconv_escape(s, g);
  1603. }
  1604. else if (!*s)
  1605. {
  1606. return 0;
  1607. }
  1608. else ++s;
  1609. }
  1610. }
  1611. };
  1612. PUGI__FN strconv_attribute_t get_strconv_attribute(unsigned int optmask)
  1613. {
  1614. PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_wconv_attribute == 0x40 && parse_wnorm_attribute == 0x80);
  1615. switch ((optmask >> 4) & 15) // get bitmask for flags (wconv wnorm eol escapes)
  1616. {
  1617. case 0: return strconv_attribute_impl<opt_false>::parse_simple;
  1618. case 1: return strconv_attribute_impl<opt_true>::parse_simple;
  1619. case 2: return strconv_attribute_impl<opt_false>::parse_eol;
  1620. case 3: return strconv_attribute_impl<opt_true>::parse_eol;
  1621. case 4: return strconv_attribute_impl<opt_false>::parse_wconv;
  1622. case 5: return strconv_attribute_impl<opt_true>::parse_wconv;
  1623. case 6: return strconv_attribute_impl<opt_false>::parse_wconv;
  1624. case 7: return strconv_attribute_impl<opt_true>::parse_wconv;
  1625. case 8: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1626. case 9: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1627. case 10: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1628. case 11: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1629. case 12: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1630. case 13: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1631. case 14: return strconv_attribute_impl<opt_false>::parse_wnorm;
  1632. case 15: return strconv_attribute_impl<opt_true>::parse_wnorm;
  1633. default: return 0; // should not get here
  1634. }
  1635. }
  1636. inline xml_parse_result make_parse_result(xml_parse_status status, ptrdiff_t offset = 0)
  1637. {
  1638. xml_parse_result result;
  1639. result.status = status;
  1640. result.offset = offset;
  1641. return result;
  1642. }
  1643. struct xml_parser
  1644. {
  1645. xml_allocator alloc;
  1646. char_t* error_offset;
  1647. xml_parse_status error_status;
  1648. // Parser utilities.
  1649. #define PUGI__SKIPWS() { while (PUGI__IS_CHARTYPE(*s, ct_space)) ++s; }
  1650. #define PUGI__OPTSET(OPT) ( optmsk & (OPT) )
  1651. #define PUGI__PUSHNODE(TYPE) { cursor = append_node(cursor, alloc, TYPE); if (!cursor) PUGI__THROW_ERROR(status_out_of_memory, s); }
  1652. #define PUGI__POPNODE() { cursor = cursor->parent; }
  1653. #define PUGI__SCANFOR(X) { while (*s != 0 && !(X)) ++s; }
  1654. #define PUGI__SCANWHILE(X) { while ((X)) ++s; }
  1655. #define PUGI__ENDSEG() { ch = *s; *s = 0; ++s; }
  1656. #define PUGI__THROW_ERROR(err, m) return error_offset = m, error_status = err, static_cast<char_t*>(0)
  1657. #define PUGI__CHECK_ERROR(err, m) { if (*s == 0) PUGI__THROW_ERROR(err, m); }
  1658. xml_parser(const xml_allocator& alloc_): alloc(alloc_), error_offset(0), error_status(status_ok)
  1659. {
  1660. }
  1661. // DOCTYPE consists of nested sections of the following possible types:
  1662. // <!-- ... -->, <? ... ?>, "...", '...'
  1663. // <![...]]>
  1664. // <!...>
  1665. // First group can not contain nested groups
  1666. // Second group can contain nested groups of the same type
  1667. // Third group can contain all other groups
  1668. char_t* parse_doctype_primitive(char_t* s)
  1669. {
  1670. if (*s == '"' || *s == '\'')
  1671. {
  1672. // quoted string
  1673. char_t ch = *s++;
  1674. PUGI__SCANFOR(*s == ch);
  1675. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  1676. s++;
  1677. }
  1678. else if (s[0] == '<' && s[1] == '?')
  1679. {
  1680. // <? ... ?>
  1681. s += 2;
  1682. PUGI__SCANFOR(s[0] == '?' && s[1] == '>'); // no need for ENDSWITH because ?> can't terminate proper doctype
  1683. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  1684. s += 2;
  1685. }
  1686. else if (s[0] == '<' && s[1] == '!' && s[2] == '-' && s[3] == '-')
  1687. {
  1688. s += 4;
  1689. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && s[2] == '>'); // no need for ENDSWITH because --> can't terminate proper doctype
  1690. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  1691. s += 4;
  1692. }
  1693. else PUGI__THROW_ERROR(status_bad_doctype, s);
  1694. return s;
  1695. }
  1696. char_t* parse_doctype_ignore(char_t* s)
  1697. {
  1698. assert(s[0] == '<' && s[1] == '!' && s[2] == '[');
  1699. s++;
  1700. while (*s)
  1701. {
  1702. if (s[0] == '<' && s[1] == '!' && s[2] == '[')
  1703. {
  1704. // nested ignore section
  1705. s = parse_doctype_ignore(s);
  1706. if (!s) return s;
  1707. }
  1708. else if (s[0] == ']' && s[1] == ']' && s[2] == '>')
  1709. {
  1710. // ignore section end
  1711. s += 3;
  1712. return s;
  1713. }
  1714. else s++;
  1715. }
  1716. PUGI__THROW_ERROR(status_bad_doctype, s);
  1717. }
  1718. char_t* parse_doctype_group(char_t* s, char_t endch, bool toplevel)
  1719. {
  1720. assert(s[0] == '<' && s[1] == '!');
  1721. s++;
  1722. while (*s)
  1723. {
  1724. if (s[0] == '<' && s[1] == '!' && s[2] != '-')
  1725. {
  1726. if (s[2] == '[')
  1727. {
  1728. // ignore
  1729. s = parse_doctype_ignore(s);
  1730. if (!s) return s;
  1731. }
  1732. else
  1733. {
  1734. // some control group
  1735. s = parse_doctype_group(s, endch, false);
  1736. if (!s) return s;
  1737. }
  1738. }
  1739. else if (s[0] == '<' || s[0] == '"' || s[0] == '\'')
  1740. {
  1741. // unknown tag (forbidden), or some primitive group
  1742. s = parse_doctype_primitive(s);
  1743. if (!s) return s;
  1744. }
  1745. else if (*s == '>')
  1746. {
  1747. s++;
  1748. return s;
  1749. }
  1750. else s++;
  1751. }
  1752. if (!toplevel || endch != '>') PUGI__THROW_ERROR(status_bad_doctype, s);
  1753. return s;
  1754. }
  1755. char_t* parse_exclamation(char_t* s, xml_node_struct* cursor, unsigned int optmsk, char_t endch)
  1756. {
  1757. // parse node contents, starting with exclamation mark
  1758. ++s;
  1759. if (*s == '-') // '<!-...'
  1760. {
  1761. ++s;
  1762. if (*s == '-') // '<!--...'
  1763. {
  1764. ++s;
  1765. if (PUGI__OPTSET(parse_comments))
  1766. {
  1767. PUGI__PUSHNODE(node_comment); // Append a new node on the tree.
  1768. cursor->value = s; // Save the offset.
  1769. }
  1770. if (PUGI__OPTSET(parse_eol) && PUGI__OPTSET(parse_comments))
  1771. {
  1772. s = strconv_comment(s, endch);
  1773. if (!s) PUGI__THROW_ERROR(status_bad_comment, cursor->value);
  1774. }
  1775. else
  1776. {
  1777. // Scan for terminating '-->'.
  1778. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && ENDSWITH(s[2], '>'));
  1779. PUGI__CHECK_ERROR(status_bad_comment, s);
  1780. if (PUGI__OPTSET(parse_comments))
  1781. *s = 0; // Zero-terminate this segment at the first terminating '-'.
  1782. s += (s[2] == '>' ? 3 : 2); // Step over the '\0->'.
  1783. }
  1784. }
  1785. else PUGI__THROW_ERROR(status_bad_comment, s);
  1786. }
  1787. else if (*s == '[')
  1788. {
  1789. // '<![CDATA[...'
  1790. if (*++s=='C' && *++s=='D' && *++s=='A' && *++s=='T' && *++s=='A' && *++s == '[')
  1791. {
  1792. ++s;
  1793. if (PUGI__OPTSET(parse_cdata))
  1794. {
  1795. PUGI__PUSHNODE(node_cdata); // Append a new node on the tree.
  1796. cursor->value = s; // Save the offset.
  1797. if (PUGI__OPTSET(parse_eol))
  1798. {
  1799. s = strconv_cdata(s, endch);
  1800. if (!s) PUGI__THROW_ERROR(status_bad_cdata, cursor->value);
  1801. }
  1802. else
  1803. {
  1804. // Scan for terminating ']]>'.
  1805. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && ENDSWITH(s[2], '>'));
  1806. PUGI__CHECK_ERROR(status_bad_cdata, s);
  1807. *s++ = 0; // Zero-terminate this segment.
  1808. }
  1809. }
  1810. else // Flagged for discard, but we still have to scan for the terminator.
  1811. {
  1812. // Scan for terminating ']]>'.
  1813. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && ENDSWITH(s[2], '>'));
  1814. PUGI__CHECK_ERROR(status_bad_cdata, s);
  1815. ++s;
  1816. }
  1817. s += (s[1] == '>' ? 2 : 1); // Step over the last ']>'.
  1818. }
  1819. else PUGI__THROW_ERROR(status_bad_cdata, s);
  1820. }
  1821. else if (s[0] == 'D' && s[1] == 'O' && s[2] == 'C' && s[3] == 'T' && s[4] == 'Y' && s[5] == 'P' && ENDSWITH(s[6], 'E'))
  1822. {
  1823. s -= 2;
  1824. if (cursor->parent) PUGI__THROW_ERROR(status_bad_doctype, s);
  1825. char_t* mark = s + 9;
  1826. s = parse_doctype_group(s, endch, true);
  1827. if (!s) return s;
  1828. if (PUGI__OPTSET(parse_doctype))
  1829. {
  1830. while (PUGI__IS_CHARTYPE(*mark, ct_space)) ++mark;
  1831. PUGI__PUSHNODE(node_doctype);
  1832. cursor->value = mark;
  1833. assert((s[0] == 0 && endch == '>') || s[-1] == '>');
  1834. s[*s == 0 ? 0 : -1] = 0;
  1835. PUGI__POPNODE();
  1836. }
  1837. }
  1838. else if (*s == 0 && endch == '-') PUGI__THROW_ERROR(status_bad_comment, s);
  1839. else if (*s == 0 && endch == '[') PUGI__THROW_ERROR(status_bad_cdata, s);
  1840. else PUGI__THROW_ERROR(status_unrecognized_tag, s);
  1841. return s;
  1842. }
  1843. char_t* parse_question(char_t* s, xml_node_struct*& ref_cursor, unsigned int optmsk, char_t endch)
  1844. {
  1845. // load into registers
  1846. xml_node_struct* cursor = ref_cursor;
  1847. char_t ch = 0;
  1848. // parse node contents, starting with question mark
  1849. ++s;
  1850. // read PI target
  1851. char_t* target = s;
  1852. if (!PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_pi, s);
  1853. PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol));
  1854. PUGI__CHECK_ERROR(status_bad_pi, s);
  1855. // determine node type; stricmp / strcasecmp is not portable
  1856. bool declaration = (target[0] | ' ') == 'x' && (target[1] | ' ') == 'm' && (target[2] | ' ') == 'l' && target + 3 == s;
  1857. if (declaration ? PUGI__OPTSET(parse_declaration) : PUGI__OPTSET(parse_pi))
  1858. {
  1859. if (declaration)
  1860. {
  1861. // disallow non top-level declarations
  1862. if (cursor->parent) PUGI__THROW_ERROR(status_bad_pi, s);
  1863. PUGI__PUSHNODE(node_declaration);
  1864. }
  1865. else
  1866. {
  1867. PUGI__PUSHNODE(node_pi);
  1868. }
  1869. cursor->name = target;
  1870. PUGI__ENDSEG();
  1871. // parse value/attributes
  1872. if (ch == '?')
  1873. {
  1874. // empty node
  1875. if (!ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_pi, s);
  1876. s += (*s == '>');
  1877. PUGI__POPNODE();
  1878. }
  1879. else if (PUGI__IS_CHARTYPE(ch, ct_space))
  1880. {
  1881. PUGI__SKIPWS();
  1882. // scan for tag end
  1883. char_t* value = s;
  1884. PUGI__SCANFOR(s[0] == '?' && ENDSWITH(s[1], '>'));
  1885. PUGI__CHECK_ERROR(status_bad_pi, s);
  1886. if (declaration)
  1887. {
  1888. // replace ending ? with / so that 'element' terminates properly
  1889. *s = '/';
  1890. // we exit from this function with cursor at node_declaration, which is a signal to parse() to go to LOC_ATTRIBUTES
  1891. s = value;
  1892. }
  1893. else
  1894. {
  1895. // store value and step over >
  1896. cursor->value = value;
  1897. PUGI__POPNODE();
  1898. PUGI__ENDSEG();
  1899. s += (*s == '>');
  1900. }
  1901. }
  1902. else PUGI__THROW_ERROR(status_bad_pi, s);
  1903. }
  1904. else
  1905. {
  1906. // scan for tag end
  1907. PUGI__SCANFOR(s[0] == '?' && ENDSWITH(s[1], '>'));
  1908. PUGI__CHECK_ERROR(status_bad_pi, s);
  1909. s += (s[1] == '>' ? 2 : 1);
  1910. }
  1911. // store from registers
  1912. ref_cursor = cursor;
  1913. return s;
  1914. }
  1915. char_t* parse(char_t* s, xml_node_struct* xmldoc, unsigned int optmsk, char_t endch)
  1916. {
  1917. strconv_attribute_t strconv_attribute = get_strconv_attribute(optmsk);
  1918. strconv_pcdata_t strconv_pcdata = get_strconv_pcdata(optmsk);
  1919. char_t ch = 0;
  1920. xml_node_struct* cursor = xmldoc;
  1921. char_t* mark = s;
  1922. while (*s != 0)
  1923. {
  1924. if (*s == '<')
  1925. {
  1926. ++s;
  1927. LOC_TAG:
  1928. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // '<#...'
  1929. {
  1930. PUGI__PUSHNODE(node_element); // Append a new node to the tree.
  1931. cursor->name = s;
  1932. PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol)); // Scan for a terminator.
  1933. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
  1934. if (ch == '>')
  1935. {
  1936. // end of tag
  1937. }
  1938. else if (PUGI__IS_CHARTYPE(ch, ct_space))
  1939. {
  1940. LOC_ATTRIBUTES:
  1941. while (true)
  1942. {
  1943. PUGI__SKIPWS(); // Eat any whitespace.
  1944. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // <... #...
  1945. {
  1946. xml_attribute_struct* a = append_attribute_ll(cursor, alloc); // Make space for this attribute.
  1947. if (!a) PUGI__THROW_ERROR(status_out_of_memory, s);
  1948. a->name = s; // Save the offset.
  1949. PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol)); // Scan for a terminator.
  1950. PUGI__CHECK_ERROR(status_bad_attribute, s); //$ redundant, left for performance
  1951. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
  1952. PUGI__CHECK_ERROR(status_bad_attribute, s); //$ redundant, left for performance
  1953. if (PUGI__IS_CHARTYPE(ch, ct_space))
  1954. {
  1955. PUGI__SKIPWS(); // Eat any whitespace.
  1956. PUGI__CHECK_ERROR(status_bad_attribute, s); //$ redundant, left for performance
  1957. ch = *s;
  1958. ++s;
  1959. }
  1960. if (ch == '=') // '<... #=...'
  1961. {
  1962. PUGI__SKIPWS(); // Eat any whitespace.
  1963. if (*s == '"' || *s == '\'') // '<... #="...'
  1964. {
  1965. ch = *s; // Save quote char to avoid breaking on "''" -or- '""'.
  1966. ++s; // Step over the quote.
  1967. a->value = s; // Save the offset.
  1968. s = strconv_attribute(s, ch);
  1969. if (!s) PUGI__THROW_ERROR(status_bad_attribute, a->value);
  1970. // After this line the loop continues from the start;
  1971. // Whitespaces, / and > are ok, symbols and EOF are wrong,
  1972. // everything else will be detected
  1973. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_attribute, s);
  1974. }
  1975. else PUGI__THROW_ERROR(status_bad_attribute, s);
  1976. }
  1977. else PUGI__THROW_ERROR(status_bad_attribute, s);
  1978. }
  1979. else if (*s == '/')
  1980. {
  1981. ++s;
  1982. if (*s == '>')
  1983. {
  1984. PUGI__POPNODE();
  1985. s++;
  1986. break;
  1987. }
  1988. else if (*s == 0 && endch == '>')
  1989. {
  1990. PUGI__POPNODE();
  1991. break;
  1992. }
  1993. else PUGI__THROW_ERROR(status_bad_start_element, s);
  1994. }
  1995. else if (*s == '>')
  1996. {
  1997. ++s;
  1998. break;
  1999. }
  2000. else if (*s == 0 && endch == '>')
  2001. {
  2002. break;
  2003. }
  2004. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2005. }
  2006. // !!!
  2007. }
  2008. else if (ch == '/') // '<#.../'
  2009. {
  2010. if (!ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_start_element, s);
  2011. PUGI__POPNODE(); // Pop.
  2012. s += (*s == '>');
  2013. }
  2014. else if (ch == 0)
  2015. {
  2016. // we stepped over null terminator, backtrack & handle closing tag
  2017. --s;
  2018. if (endch != '>') PUGI__THROW_ERROR(status_bad_start_element, s);
  2019. }
  2020. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2021. }
  2022. else if (*s == '/')
  2023. {
  2024. ++s;
  2025. char_t* name = cursor->name;
  2026. if (!name) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2027. while (PUGI__IS_CHARTYPE(*s, ct_symbol))
  2028. {
  2029. if (*s++ != *name++) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2030. }
  2031. if (*name)
  2032. {
  2033. if (*s == 0 && name[0] == endch && name[1] == 0) PUGI__THROW_ERROR(status_bad_end_element, s);
  2034. else PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2035. }
  2036. PUGI__POPNODE(); // Pop.
  2037. PUGI__SKIPWS();
  2038. if (*s == 0)
  2039. {
  2040. if (endch != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
  2041. }
  2042. else
  2043. {
  2044. if (*s != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
  2045. ++s;
  2046. }
  2047. }
  2048. else if (*s == '?') // '<?...'
  2049. {
  2050. s = parse_question(s, cursor, optmsk, endch);
  2051. if (!s) return s;
  2052. assert(cursor);
  2053. if ((cursor->header & xml_memory_page_type_mask) + 1 == node_declaration) goto LOC_ATTRIBUTES;
  2054. }
  2055. else if (*s == '!') // '<!...'
  2056. {
  2057. s = parse_exclamation(s, cursor, optmsk, endch);
  2058. if (!s) return s;
  2059. }
  2060. else if (*s == 0 && endch == '?') PUGI__THROW_ERROR(status_bad_pi, s);
  2061. else PUGI__THROW_ERROR(status_unrecognized_tag, s);
  2062. }
  2063. else
  2064. {
  2065. mark = s; // Save this offset while searching for a terminator.
  2066. PUGI__SKIPWS(); // Eat whitespace if no genuine PCDATA here.
  2067. if (*s == '<')
  2068. {
  2069. // We skipped some whitespace characters because otherwise we would take the tag branch instead of PCDATA one
  2070. assert(mark != s);
  2071. if (!PUGI__OPTSET(parse_ws_pcdata | parse_ws_pcdata_single))
  2072. {
  2073. continue;
  2074. }
  2075. else if (PUGI__OPTSET(parse_ws_pcdata_single))
  2076. {
  2077. if (s[1] != '/' || cursor->first_child) continue;
  2078. }
  2079. }
  2080. s = mark;
  2081. if (cursor->parent)
  2082. {
  2083. PUGI__PUSHNODE(node_pcdata); // Append a new node on the tree.
  2084. cursor->value = s; // Save the offset.
  2085. s = strconv_pcdata(s);
  2086. PUGI__POPNODE(); // Pop since this is a standalone.
  2087. if (!*s) break;
  2088. }
  2089. else
  2090. {
  2091. PUGI__SCANFOR(*s == '<'); // '...<'
  2092. if (!*s) break;
  2093. ++s;
  2094. }
  2095. // We're after '<'
  2096. goto LOC_TAG;
  2097. }
  2098. }
  2099. // check that last tag is closed
  2100. if (cursor != xmldoc) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2101. return s;
  2102. }
  2103. static xml_parse_result parse(char_t* buffer, size_t length, xml_node_struct* root, unsigned int optmsk)
  2104. {
  2105. xml_document_struct* xmldoc = static_cast<xml_document_struct*>(root);
  2106. // store buffer for offset_debug
  2107. xmldoc->buffer = buffer;
  2108. // early-out for empty documents
  2109. if (length == 0) return make_parse_result(status_ok);
  2110. // create parser on stack
  2111. xml_parser parser(*xmldoc);
  2112. // save last character and make buffer zero-terminated (speeds up parsing)
  2113. char_t endch = buffer[length - 1];
  2114. buffer[length - 1] = 0;
  2115. // perform actual parsing
  2116. parser.parse(buffer, xmldoc, optmsk, endch);
  2117. xml_parse_result result = make_parse_result(parser.error_status, parser.error_offset ? parser.error_offset - buffer : 0);
  2118. assert(result.offset >= 0 && static_cast<size_t>(result.offset) <= length);
  2119. // update allocator state
  2120. *static_cast<xml_allocator*>(xmldoc) = parser.alloc;
  2121. // since we removed last character, we have to handle the only possible false positive
  2122. if (result && endch == '<')
  2123. {
  2124. // there's no possible well-formed document with < at the end
  2125. return make_parse_result(status_unrecognized_tag, length);
  2126. }
  2127. return result;
  2128. }
  2129. };
  2130. // Output facilities
  2131. PUGI__FN xml_encoding get_write_native_encoding()
  2132. {
  2133. #ifdef PUGIXML_WCHAR_MODE
  2134. return get_wchar_encoding();
  2135. #else
  2136. return encoding_utf8;
  2137. #endif
  2138. }
  2139. PUGI__FN xml_encoding get_write_encoding(xml_encoding encoding)
  2140. {
  2141. // replace wchar encoding with utf implementation
  2142. if (encoding == encoding_wchar) return get_wchar_encoding();
  2143. // replace utf16 encoding with utf16 with specific endianness
  2144. if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2145. // replace utf32 encoding with utf32 with specific endianness
  2146. if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2147. // only do autodetection if no explicit encoding is requested
  2148. if (encoding != encoding_auto) return encoding;
  2149. // assume utf8 encoding
  2150. return encoding_utf8;
  2151. }
  2152. #ifdef PUGIXML_WCHAR_MODE
  2153. PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
  2154. {
  2155. assert(length > 0);
  2156. // discard last character if it's the lead of a surrogate pair
  2157. return (sizeof(wchar_t) == 2 && static_cast<unsigned int>(static_cast<uint16_t>(data[length - 1]) - 0xD800) < 0x400) ? length - 1 : length;
  2158. }
  2159. PUGI__FN size_t convert_buffer(char_t* r_char, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)
  2160. {
  2161. // only endian-swapping is required
  2162. if (need_endian_swap_utf(encoding, get_wchar_encoding()))
  2163. {
  2164. convert_wchar_endian_swap(r_char, data, length);
  2165. return length * sizeof(char_t);
  2166. }
  2167. // convert to utf8
  2168. if (encoding == encoding_utf8)
  2169. {
  2170. uint8_t* dest = r_u8;
  2171. uint8_t* end = utf_decoder<utf8_writer>::decode_wchar_block(data, length, dest);
  2172. return static_cast<size_t>(end - dest);
  2173. }
  2174. // convert to utf16
  2175. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  2176. {
  2177. uint16_t* dest = r_u16;
  2178. // convert to native utf16
  2179. uint16_t* end = utf_decoder<utf16_writer>::decode_wchar_block(data, length, dest);
  2180. // swap if necessary
  2181. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2182. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2183. return static_cast<size_t>(end - dest) * sizeof(uint16_t);
  2184. }
  2185. // convert to utf32
  2186. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  2187. {
  2188. uint32_t* dest = r_u32;
  2189. // convert to native utf32
  2190. uint32_t* end = utf_decoder<utf32_writer>::decode_wchar_block(data, length, dest);
  2191. // swap if necessary
  2192. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2193. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2194. return static_cast<size_t>(end - dest) * sizeof(uint32_t);
  2195. }
  2196. // convert to latin1
  2197. if (encoding == encoding_latin1)
  2198. {
  2199. uint8_t* dest = r_u8;
  2200. uint8_t* end = utf_decoder<latin1_writer>::decode_wchar_block(data, length, dest);
  2201. return static_cast<size_t>(end - dest);
  2202. }
  2203. assert(!"Invalid encoding");
  2204. return 0;
  2205. }
  2206. #else
  2207. PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
  2208. {
  2209. assert(length > 4);
  2210. for (size_t i = 1; i <= 4; ++i)
  2211. {
  2212. uint8_t ch = static_cast<uint8_t>(data[length - i]);
  2213. // either a standalone character or a leading one
  2214. if ((ch & 0xc0) != 0x80) return length - i;
  2215. }
  2216. // there are four non-leading characters at the end, sequence tail is broken so might as well process the whole chunk
  2217. return length;
  2218. }
  2219. PUGI__FN size_t convert_buffer(char_t* /* r_char */, uint8_t* r_u8, uint16_t* r_u16, uint32_t* r_u32, const char_t* data, size_t length, xml_encoding encoding)
  2220. {
  2221. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  2222. {
  2223. uint16_t* dest = r_u16;
  2224. // convert to native utf16
  2225. uint16_t* end = utf_decoder<utf16_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);
  2226. // swap if necessary
  2227. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2228. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2229. return static_cast<size_t>(end - dest) * sizeof(uint16_t);
  2230. }
  2231. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  2232. {
  2233. uint32_t* dest = r_u32;
  2234. // convert to native utf32
  2235. uint32_t* end = utf_decoder<utf32_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);
  2236. // swap if necessary
  2237. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2238. if (native_encoding != encoding) convert_utf_endian_swap(dest, dest, static_cast<size_t>(end - dest));
  2239. return static_cast<size_t>(end - dest) * sizeof(uint32_t);
  2240. }
  2241. if (encoding == encoding_latin1)
  2242. {
  2243. uint8_t* dest = r_u8;
  2244. uint8_t* end = utf_decoder<latin1_writer>::decode_utf8_block(reinterpret_cast<const uint8_t*>(data), length, dest);
  2245. return static_cast<size_t>(end - dest);
  2246. }
  2247. assert(!"Invalid encoding");
  2248. return 0;
  2249. }
  2250. #endif
  2251. class xml_buffered_writer
  2252. {
  2253. xml_buffered_writer(const xml_buffered_writer&);
  2254. xml_buffered_writer& operator=(const xml_buffered_writer&);
  2255. public:
  2256. xml_buffered_writer(xml_writer& writer_, xml_encoding user_encoding): writer(writer_), bufsize(0), encoding(get_write_encoding(user_encoding))
  2257. {
  2258. PUGI__STATIC_ASSERT(bufcapacity >= 8);
  2259. }
  2260. ~xml_buffered_writer()
  2261. {
  2262. flush();
  2263. }
  2264. void flush()
  2265. {
  2266. flush(buffer, bufsize);
  2267. bufsize = 0;
  2268. }
  2269. void flush(const char_t* data, size_t size)
  2270. {
  2271. if (size == 0) return;
  2272. // fast path, just write data
  2273. if (encoding == get_write_native_encoding())
  2274. writer.write(data, size * sizeof(char_t));
  2275. else
  2276. {
  2277. // convert chunk
  2278. size_t result = convert_buffer(scratch.data_char, scratch.data_u8, scratch.data_u16, scratch.data_u32, data, size, encoding);
  2279. assert(result <= sizeof(scratch));
  2280. // write data
  2281. writer.write(scratch.data_u8, result);
  2282. }
  2283. }
  2284. void write(const char_t* data, size_t length)
  2285. {
  2286. if (bufsize + length > bufcapacity)
  2287. {
  2288. // flush the remaining buffer contents
  2289. flush();
  2290. // handle large chunks
  2291. if (length > bufcapacity)
  2292. {
  2293. if (encoding == get_write_native_encoding())
  2294. {
  2295. // fast path, can just write data chunk
  2296. writer.write(data, length * sizeof(char_t));
  2297. return;
  2298. }
  2299. // need to convert in suitable chunks
  2300. while (length > bufcapacity)
  2301. {
  2302. // get chunk size by selecting such number of characters that are guaranteed to fit into scratch buffer
  2303. // and form a complete codepoint sequence (i.e. discard start of last codepoint if necessary)
  2304. size_t chunk_size = get_valid_length(data, bufcapacity);
  2305. // convert chunk and write
  2306. flush(data, chunk_size);
  2307. // iterate
  2308. data += chunk_size;
  2309. length -= chunk_size;
  2310. }
  2311. // small tail is copied below
  2312. bufsize = 0;
  2313. }
  2314. }
  2315. memcpy(buffer + bufsize, data, length * sizeof(char_t));
  2316. bufsize += length;
  2317. }
  2318. void write(const char_t* data)
  2319. {
  2320. write(data, strlength(data));
  2321. }
  2322. void write(char_t d0)
  2323. {
  2324. if (bufsize + 1 > bufcapacity) flush();
  2325. buffer[bufsize + 0] = d0;
  2326. bufsize += 1;
  2327. }
  2328. void write(char_t d0, char_t d1)
  2329. {
  2330. if (bufsize + 2 > bufcapacity) flush();
  2331. buffer[bufsize + 0] = d0;
  2332. buffer[bufsize + 1] = d1;
  2333. bufsize += 2;
  2334. }
  2335. void write(char_t d0, char_t d1, char_t d2)
  2336. {
  2337. if (bufsize + 3 > bufcapacity) flush();
  2338. buffer[bufsize + 0] = d0;
  2339. buffer[bufsize + 1] = d1;
  2340. buffer[bufsize + 2] = d2;
  2341. bufsize += 3;
  2342. }
  2343. void write(char_t d0, char_t d1, char_t d2, char_t d3)
  2344. {
  2345. if (bufsize + 4 > bufcapacity) flush();
  2346. buffer[bufsize + 0] = d0;
  2347. buffer[bufsize + 1] = d1;
  2348. buffer[bufsize + 2] = d2;
  2349. buffer[bufsize + 3] = d3;
  2350. bufsize += 4;
  2351. }
  2352. void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4)
  2353. {
  2354. if (bufsize + 5 > bufcapacity) flush();
  2355. buffer[bufsize + 0] = d0;
  2356. buffer[bufsize + 1] = d1;
  2357. buffer[bufsize + 2] = d2;
  2358. buffer[bufsize + 3] = d3;
  2359. buffer[bufsize + 4] = d4;
  2360. bufsize += 5;
  2361. }
  2362. void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4, char_t d5)
  2363. {
  2364. if (bufsize + 6 > bufcapacity) flush();
  2365. buffer[bufsize + 0] = d0;
  2366. buffer[bufsize + 1] = d1;
  2367. buffer[bufsize + 2] = d2;
  2368. buffer[bufsize + 3] = d3;
  2369. buffer[bufsize + 4] = d4;
  2370. buffer[bufsize + 5] = d5;
  2371. bufsize += 6;
  2372. }
  2373. // utf8 maximum expansion: x4 (-> utf32)
  2374. // utf16 maximum expansion: x2 (-> utf32)
  2375. // utf32 maximum expansion: x1
  2376. enum
  2377. {
  2378. bufcapacitybytes =
  2379. #ifdef PUGIXML_MEMORY_OUTPUT_STACK
  2380. PUGIXML_MEMORY_OUTPUT_STACK
  2381. #else
  2382. 10240
  2383. #endif
  2384. ,
  2385. bufcapacity = bufcapacitybytes / (sizeof(char_t) + 4)
  2386. };
  2387. char_t buffer[bufcapacity];
  2388. union
  2389. {
  2390. uint8_t data_u8[4 * bufcapacity];
  2391. uint16_t data_u16[2 * bufcapacity];
  2392. uint32_t data_u32[bufcapacity];
  2393. char_t data_char[bufcapacity];
  2394. } scratch;
  2395. xml_writer& writer;
  2396. size_t bufsize;
  2397. xml_encoding encoding;
  2398. };
  2399. PUGI__FN void text_output_escaped(xml_buffered_writer& writer, const char_t* s, chartypex_t type)
  2400. {
  2401. while (*s)
  2402. {
  2403. const char_t* prev = s;
  2404. // While *s is a usual symbol
  2405. while (!PUGI__IS_CHARTYPEX(*s, type)) ++s;
  2406. writer.write(prev, static_cast<size_t>(s - prev));
  2407. switch (*s)
  2408. {
  2409. case 0: break;
  2410. case '&':
  2411. writer.write('&', 'a', 'm', 'p', ';');
  2412. ++s;
  2413. break;
  2414. case '<':
  2415. writer.write('&', 'l', 't', ';');
  2416. ++s;
  2417. break;
  2418. case '>':
  2419. writer.write('&', 'g', 't', ';');
  2420. ++s;
  2421. break;
  2422. case '"':
  2423. writer.write('&', 'q', 'u', 'o', 't', ';');
  2424. ++s;
  2425. break;
  2426. default: // s is not a usual symbol
  2427. {
  2428. unsigned int ch = static_cast<unsigned int>(*s++);
  2429. assert(ch < 32);
  2430. writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';');
  2431. }
  2432. }
  2433. }
  2434. }
  2435. PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
  2436. {
  2437. if (flags & format_no_escapes)
  2438. writer.write(s);
  2439. else
  2440. text_output_escaped(writer, s, type);
  2441. }
  2442. PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s)
  2443. {
  2444. do
  2445. {
  2446. writer.write('<', '!', '[', 'C', 'D');
  2447. writer.write('A', 'T', 'A', '[');
  2448. const char_t* prev = s;
  2449. // look for ]]> sequence - we can't output it as is since it terminates CDATA
  2450. while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s;
  2451. // skip ]] if we stopped at ]]>, > will go to the next CDATA section
  2452. if (*s) s += 2;
  2453. writer.write(prev, static_cast<size_t>(s - prev));
  2454. writer.write(']', ']', '>');
  2455. }
  2456. while (*s);
  2457. }
  2458. PUGI__FN void node_output_attributes(xml_buffered_writer& writer, const xml_node& node, unsigned int flags)
  2459. {
  2460. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  2461. for (xml_attribute a = node.first_attribute(); a; a = a.next_attribute())
  2462. {
  2463. writer.write(' ');
  2464. writer.write(a.name()[0] ? a.name() : default_name);
  2465. writer.write('=', '"');
  2466. text_output(writer, a.value(), ctx_special_attr, flags);
  2467. writer.write('"');
  2468. }
  2469. }
  2470. PUGI__FN void node_output(xml_buffered_writer& writer, const xml_node& node, const char_t* indent, unsigned int flags, unsigned int depth)
  2471. {
  2472. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  2473. if ((flags & format_indent) != 0 && (flags & format_raw) == 0)
  2474. for (unsigned int i = 0; i < depth; ++i) writer.write(indent);
  2475. switch (node.type())
  2476. {
  2477. case node_document:
  2478. {
  2479. for (xml_node n = node.first_child(); n; n = n.next_sibling())
  2480. node_output(writer, n, indent, flags, depth);
  2481. break;
  2482. }
  2483. case node_element:
  2484. {
  2485. const char_t* name = node.name()[0] ? node.name() : default_name;
  2486. writer.write('<');
  2487. writer.write(name);
  2488. node_output_attributes(writer, node, flags);
  2489. if (flags & format_raw)
  2490. {
  2491. if (!node.first_child())
  2492. writer.write(' ', '/', '>');
  2493. else
  2494. {
  2495. writer.write('>');
  2496. for (xml_node n = node.first_child(); n; n = n.next_sibling())
  2497. node_output(writer, n, indent, flags, depth + 1);
  2498. writer.write('<', '/');
  2499. writer.write(name);
  2500. writer.write('>');
  2501. }
  2502. }
  2503. else if (!node.first_child())
  2504. writer.write(' ', '/', '>', '\n');
  2505. else if (node.first_child() == node.last_child() && (node.first_child().type() == node_pcdata || node.first_child().type() == node_cdata))
  2506. {
  2507. writer.write('>');
  2508. if (node.first_child().type() == node_pcdata)
  2509. text_output(writer, node.first_child().value(), ctx_special_pcdata, flags);
  2510. else
  2511. text_output_cdata(writer, node.first_child().value());
  2512. writer.write('<', '/');
  2513. writer.write(name);
  2514. writer.write('>', '\n');
  2515. }
  2516. else
  2517. {
  2518. writer.write('>', '\n');
  2519. for (xml_node n = node.first_child(); n; n = n.next_sibling())
  2520. node_output(writer, n, indent, flags, depth + 1);
  2521. if ((flags & format_indent) != 0 && (flags & format_raw) == 0)
  2522. for (unsigned int i = 0; i < depth; ++i) writer.write(indent);
  2523. writer.write('<', '/');
  2524. writer.write(name);
  2525. writer.write('>', '\n');
  2526. }
  2527. break;
  2528. }
  2529. case node_pcdata:
  2530. text_output(writer, node.value(), ctx_special_pcdata, flags);
  2531. if ((flags & format_raw) == 0) writer.write('\n');
  2532. break;
  2533. case node_cdata:
  2534. text_output_cdata(writer, node.value());
  2535. if ((flags & format_raw) == 0) writer.write('\n');
  2536. break;
  2537. case node_comment:
  2538. writer.write('<', '!', '-', '-');
  2539. writer.write(node.value());
  2540. writer.write('-', '-', '>');
  2541. if ((flags & format_raw) == 0) writer.write('\n');
  2542. break;
  2543. case node_pi:
  2544. case node_declaration:
  2545. writer.write('<', '?');
  2546. writer.write(node.name()[0] ? node.name() : default_name);
  2547. if (node.type() == node_declaration)
  2548. {
  2549. node_output_attributes(writer, node, flags);
  2550. }
  2551. else if (node.value()[0])
  2552. {
  2553. writer.write(' ');
  2554. writer.write(node.value());
  2555. }
  2556. writer.write('?', '>');
  2557. if ((flags & format_raw) == 0) writer.write('\n');
  2558. break;
  2559. case node_doctype:
  2560. writer.write('<', '!', 'D', 'O', 'C');
  2561. writer.write('T', 'Y', 'P', 'E');
  2562. if (node.value()[0])
  2563. {
  2564. writer.write(' ');
  2565. writer.write(node.value());
  2566. }
  2567. writer.write('>');
  2568. if ((flags & format_raw) == 0) writer.write('\n');
  2569. break;
  2570. default:
  2571. assert(!"Invalid node type");
  2572. }
  2573. }
  2574. inline bool has_declaration(const xml_node& node)
  2575. {
  2576. for (xml_node child = node.first_child(); child; child = child.next_sibling())
  2577. {
  2578. xml_node_type type = child.type();
  2579. if (type == node_declaration) return true;
  2580. if (type == node_element) return false;
  2581. }
  2582. return false;
  2583. }
  2584. inline bool allow_insert_child(xml_node_type parent, xml_node_type child)
  2585. {
  2586. if (parent != node_document && parent != node_element) return false;
  2587. if (child == node_document || child == node_null) return false;
  2588. if (parent != node_document && (child == node_declaration || child == node_doctype)) return false;
  2589. return true;
  2590. }
  2591. PUGI__FN void recursive_copy_skip(xml_node& dest, const xml_node& source, const xml_node& skip)
  2592. {
  2593. assert(dest.type() == source.type());
  2594. switch (source.type())
  2595. {
  2596. case node_element:
  2597. {
  2598. dest.set_name(source.name());
  2599. for (xml_attribute a = source.first_attribute(); a; a = a.next_attribute())
  2600. dest.append_attribute(a.name()).set_value(a.value());
  2601. for (xml_node c = source.first_child(); c; c = c.next_sibling())
  2602. {
  2603. if (c == skip) continue;
  2604. xml_node cc = dest.append_child(c.type());
  2605. assert(cc);
  2606. recursive_copy_skip(cc, c, skip);
  2607. }
  2608. break;
  2609. }
  2610. case node_pcdata:
  2611. case node_cdata:
  2612. case node_comment:
  2613. case node_doctype:
  2614. dest.set_value(source.value());
  2615. break;
  2616. case node_pi:
  2617. dest.set_name(source.name());
  2618. dest.set_value(source.value());
  2619. break;
  2620. case node_declaration:
  2621. {
  2622. dest.set_name(source.name());
  2623. for (xml_attribute a = source.first_attribute(); a; a = a.next_attribute())
  2624. dest.append_attribute(a.name()).set_value(a.value());
  2625. break;
  2626. }
  2627. default:
  2628. assert(!"Invalid node type");
  2629. }
  2630. }
  2631. inline bool is_text_node(xml_node_struct* node)
  2632. {
  2633. xml_node_type type = static_cast<xml_node_type>((node->header & impl::xml_memory_page_type_mask) + 1);
  2634. return type == node_pcdata || type == node_cdata;
  2635. }
  2636. // get value with conversion functions
  2637. PUGI__FN int get_value_int(const char_t* value, int def)
  2638. {
  2639. if (!value) return def;
  2640. #ifdef PUGIXML_WCHAR_MODE
  2641. return static_cast<int>(wcstol(value, 0, 10));
  2642. #else
  2643. return static_cast<int>(strtol(value, 0, 10));
  2644. #endif
  2645. }
  2646. PUGI__FN unsigned int get_value_uint(const char_t* value, unsigned int def)
  2647. {
  2648. if (!value) return def;
  2649. #ifdef PUGIXML_WCHAR_MODE
  2650. return static_cast<unsigned int>(wcstoul(value, 0, 10));
  2651. #else
  2652. return static_cast<unsigned int>(strtoul(value, 0, 10));
  2653. #endif
  2654. }
  2655. PUGI__FN double get_value_double(const char_t* value, double def)
  2656. {
  2657. if (!value) return def;
  2658. #ifdef PUGIXML_WCHAR_MODE
  2659. return wcstod(value, 0);
  2660. #else
  2661. return strtod(value, 0);
  2662. #endif
  2663. }
  2664. PUGI__FN float get_value_float(const char_t* value, float def)
  2665. {
  2666. if (!value) return def;
  2667. #ifdef PUGIXML_WCHAR_MODE
  2668. return static_cast<float>(wcstod(value, 0));
  2669. #else
  2670. return static_cast<float>(strtod(value, 0));
  2671. #endif
  2672. }
  2673. PUGI__FN bool get_value_bool(const char_t* value, bool def)
  2674. {
  2675. if (!value) return def;
  2676. // only look at first char
  2677. char_t first = *value;
  2678. // 1*, t* (true), T* (True), y* (yes), Y* (YES)
  2679. return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');
  2680. }
  2681. // set value with conversion functions
  2682. PUGI__FN bool set_value_buffer(char_t*& dest, uintptr_t& header, uintptr_t header_mask, char (&buf)[128])
  2683. {
  2684. #ifdef PUGIXML_WCHAR_MODE
  2685. char_t wbuf[128];
  2686. impl::widen_ascii(wbuf, buf);
  2687. return strcpy_insitu(dest, header, header_mask, wbuf);
  2688. #else
  2689. return strcpy_insitu(dest, header, header_mask, buf);
  2690. #endif
  2691. }
  2692. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, int value)
  2693. {
  2694. char buf[128];
  2695. sprintf(buf, "%d", value);
  2696. return set_value_buffer(dest, header, header_mask, buf);
  2697. }
  2698. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, unsigned int value)
  2699. {
  2700. char buf[128];
  2701. sprintf(buf, "%u", value);
  2702. return set_value_buffer(dest, header, header_mask, buf);
  2703. }
  2704. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, double value)
  2705. {
  2706. char buf[128];
  2707. sprintf(buf, "%g", value);
  2708. return set_value_buffer(dest, header, header_mask, buf);
  2709. }
  2710. PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, bool value)
  2711. {
  2712. return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
  2713. }
  2714. // we need to get length of entire file to load it in memory; the only (relatively) sane way to do it is via seek/tell trick
  2715. PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result)
  2716. {
  2717. #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
  2718. // there are 64-bit versions of fseek/ftell, let's use them
  2719. typedef __int64 length_type;
  2720. _fseeki64(file, 0, SEEK_END);
  2721. length_type length = _ftelli64(file);
  2722. _fseeki64(file, 0, SEEK_SET);
  2723. #elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && !defined(__STRICT_ANSI__)
  2724. // there are 64-bit versions of fseek/ftell, let's use them
  2725. typedef off64_t length_type;
  2726. fseeko64(file, 0, SEEK_END);
  2727. length_type length = ftello64(file);
  2728. fseeko64(file, 0, SEEK_SET);
  2729. #else
  2730. // if this is a 32-bit OS, long is enough; if this is a unix system, long is 64-bit, which is enough; otherwise we can't do anything anyway.
  2731. typedef long length_type;
  2732. fseek(file, 0, SEEK_END);
  2733. length_type length = ftell(file);
  2734. fseek(file, 0, SEEK_SET);
  2735. #endif
  2736. // check for I/O errors
  2737. if (length < 0) return status_io_error;
  2738. // check for overflow
  2739. size_t result = static_cast<size_t>(length);
  2740. if (static_cast<length_type>(result) != length) return status_out_of_memory;
  2741. // finalize
  2742. out_result = result;
  2743. return status_ok;
  2744. }
  2745. PUGI__FN xml_parse_result load_file_impl(xml_document& doc, FILE* file, unsigned int options, xml_encoding encoding)
  2746. {
  2747. if (!file) return make_parse_result(status_file_not_found);
  2748. // get file size (can result in I/O errors)
  2749. size_t size = 0;
  2750. xml_parse_status size_status = get_file_size(file, size);
  2751. if (size_status != status_ok)
  2752. {
  2753. fclose(file);
  2754. return make_parse_result(size_status);
  2755. }
  2756. // allocate buffer for the whole file
  2757. char* contents = static_cast<char*>(xml_memory::allocate(size > 0 ? size : 1));
  2758. if (!contents)
  2759. {
  2760. fclose(file);
  2761. return make_parse_result(status_out_of_memory);
  2762. }
  2763. // read file in memory
  2764. size_t read_size = fread(contents, 1, size, file);
  2765. fclose(file);
  2766. if (read_size != size)
  2767. {
  2768. xml_memory::deallocate(contents);
  2769. return make_parse_result(status_io_error);
  2770. }
  2771. return doc.load_buffer_inplace_own(contents, size, options, encoding);
  2772. }
  2773. #ifndef PUGIXML_NO_STL
  2774. template <typename T> struct xml_stream_chunk
  2775. {
  2776. static xml_stream_chunk* create()
  2777. {
  2778. void* memory = xml_memory::allocate(sizeof(xml_stream_chunk));
  2779. return new (memory) xml_stream_chunk();
  2780. }
  2781. static void destroy(void* ptr)
  2782. {
  2783. xml_stream_chunk* chunk = static_cast<xml_stream_chunk*>(ptr);
  2784. // free chunk chain
  2785. while (chunk)
  2786. {
  2787. xml_stream_chunk* next = chunk->next;
  2788. xml_memory::deallocate(chunk);
  2789. chunk = next;
  2790. }
  2791. }
  2792. xml_stream_chunk(): next(0), size(0)
  2793. {
  2794. }
  2795. xml_stream_chunk* next;
  2796. size_t size;
  2797. T data[xml_memory_page_size / sizeof(T)];
  2798. };
  2799. template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
  2800. {
  2801. buffer_holder chunks(0, xml_stream_chunk<T>::destroy);
  2802. // read file to a chunk list
  2803. size_t total = 0;
  2804. xml_stream_chunk<T>* last = 0;
  2805. while (!stream.eof())
  2806. {
  2807. // allocate new chunk
  2808. xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create();
  2809. if (!chunk) return status_out_of_memory;
  2810. // append chunk to list
  2811. if (last) last = last->next = chunk;
  2812. else chunks.data = last = chunk;
  2813. // read data to chunk
  2814. stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T)));
  2815. chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T);
  2816. // read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors
  2817. if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
  2818. // guard against huge files (chunk size is small enough to make this overflow check work)
  2819. if (total + chunk->size < total) return status_out_of_memory;
  2820. total += chunk->size;
  2821. }
  2822. // copy chunk list to a contiguous buffer
  2823. char* buffer = static_cast<char*>(xml_memory::allocate(total));
  2824. if (!buffer) return status_out_of_memory;
  2825. char* write = buffer;
  2826. for (xml_stream_chunk<T>* chunk = static_cast<xml_stream_chunk<T>*>(chunks.data); chunk; chunk = chunk->next)
  2827. {
  2828. assert(write + chunk->size <= buffer + total);
  2829. memcpy(write, chunk->data, chunk->size);
  2830. write += chunk->size;
  2831. }
  2832. assert(write == buffer + total);
  2833. // return buffer
  2834. *out_buffer = buffer;
  2835. *out_size = total;
  2836. return status_ok;
  2837. }
  2838. template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
  2839. {
  2840. // get length of remaining data in stream
  2841. typename std::basic_istream<T>::pos_type pos = stream.tellg();
  2842. stream.seekg(0, std::ios::end);
  2843. std::streamoff length = stream.tellg() - pos;
  2844. stream.seekg(pos);
  2845. if (stream.fail() || pos < 0) return status_io_error;
  2846. // guard against huge files
  2847. size_t read_length = static_cast<size_t>(length);
  2848. if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory;
  2849. // read stream data into memory (guard against stream exceptions with buffer holder)
  2850. buffer_holder buffer(xml_memory::allocate((read_length > 0 ? read_length : 1) * sizeof(T)), xml_memory::deallocate);
  2851. if (!buffer.data) return status_out_of_memory;
  2852. stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length));
  2853. // read may set failbit | eofbit in case gcount() is less than read_length (i.e. line ending conversion), so check for other I/O errors
  2854. if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
  2855. // return buffer
  2856. size_t actual_length = static_cast<size_t>(stream.gcount());
  2857. assert(actual_length <= read_length);
  2858. *out_buffer = buffer.release();
  2859. *out_size = actual_length * sizeof(T);
  2860. return status_ok;
  2861. }
  2862. template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document& doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding)
  2863. {
  2864. void* buffer = 0;
  2865. size_t size = 0;
  2866. // load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory)
  2867. xml_parse_status status = (stream.tellg() < 0) ? load_stream_data_noseek(stream, &buffer, &size) : load_stream_data_seek(stream, &buffer, &size);
  2868. if (status != status_ok) return make_parse_result(status);
  2869. return doc.load_buffer_inplace_own(buffer, size, options, encoding);
  2870. }
  2871. #endif
  2872. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && !defined(__STRICT_ANSI__))
  2873. PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
  2874. {
  2875. return _wfopen(path, mode);
  2876. }
  2877. #else
  2878. PUGI__FN char* convert_path_heap(const wchar_t* str)
  2879. {
  2880. assert(str);
  2881. // first pass: get length in utf8 characters
  2882. size_t length = wcslen(str);
  2883. size_t size = as_utf8_begin(str, length);
  2884. // allocate resulting string
  2885. char* result = static_cast<char*>(xml_memory::allocate(size + 1));
  2886. if (!result) return 0;
  2887. // second pass: convert to utf8
  2888. as_utf8_end(result, size, str, length);
  2889. return result;
  2890. }
  2891. PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
  2892. {
  2893. // there is no standard function to open wide paths, so our best bet is to try utf8 path
  2894. char* path_utf8 = convert_path_heap(path);
  2895. if (!path_utf8) return 0;
  2896. // convert mode to ASCII (we mirror _wfopen interface)
  2897. char mode_ascii[4] = {0};
  2898. for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]);
  2899. // try to open the utf8 path
  2900. FILE* result = fopen(path_utf8, mode_ascii);
  2901. // free dummy buffer
  2902. xml_memory::deallocate(path_utf8);
  2903. return result;
  2904. }
  2905. #endif
  2906. PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding)
  2907. {
  2908. if (!file) return false;
  2909. xml_writer_file writer(file);
  2910. doc.save(writer, indent, flags, encoding);
  2911. int result = ferror(file);
  2912. fclose(file);
  2913. return result == 0;
  2914. }
  2915. PUGI__NS_END
  2916. namespace pugi
  2917. {
  2918. PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_)
  2919. {
  2920. }
  2921. PUGI__FN void xml_writer_file::write(const void* data, size_t size)
  2922. {
  2923. size_t result = fwrite(data, 1, size, static_cast<FILE*>(file));
  2924. (void)!result; // unfortunately we can't do proper error handling here
  2925. }
  2926. #ifndef PUGIXML_NO_STL
  2927. PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0)
  2928. {
  2929. }
  2930. PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream): narrow_stream(0), wide_stream(&stream)
  2931. {
  2932. }
  2933. PUGI__FN void xml_writer_stream::write(const void* data, size_t size)
  2934. {
  2935. if (narrow_stream)
  2936. {
  2937. assert(!wide_stream);
  2938. narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
  2939. }
  2940. else
  2941. {
  2942. assert(wide_stream);
  2943. assert(size % sizeof(wchar_t) == 0);
  2944. wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t)));
  2945. }
  2946. }
  2947. #endif
  2948. PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0)
  2949. {
  2950. }
  2951. PUGI__FN xml_tree_walker::~xml_tree_walker()
  2952. {
  2953. }
  2954. PUGI__FN int xml_tree_walker::depth() const
  2955. {
  2956. return _depth;
  2957. }
  2958. PUGI__FN bool xml_tree_walker::begin(xml_node&)
  2959. {
  2960. return true;
  2961. }
  2962. PUGI__FN bool xml_tree_walker::end(xml_node&)
  2963. {
  2964. return true;
  2965. }
  2966. PUGI__FN xml_attribute::xml_attribute(): _attr(0)
  2967. {
  2968. }
  2969. PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr)
  2970. {
  2971. }
  2972. PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***)
  2973. {
  2974. }
  2975. PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const
  2976. {
  2977. return _attr ? unspecified_bool_xml_attribute : 0;
  2978. }
  2979. PUGI__FN bool xml_attribute::operator!() const
  2980. {
  2981. return !_attr;
  2982. }
  2983. PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const
  2984. {
  2985. return (_attr == r._attr);
  2986. }
  2987. PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const
  2988. {
  2989. return (_attr != r._attr);
  2990. }
  2991. PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const
  2992. {
  2993. return (_attr < r._attr);
  2994. }
  2995. PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const
  2996. {
  2997. return (_attr > r._attr);
  2998. }
  2999. PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const
  3000. {
  3001. return (_attr <= r._attr);
  3002. }
  3003. PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const
  3004. {
  3005. return (_attr >= r._attr);
  3006. }
  3007. PUGI__FN xml_attribute xml_attribute::next_attribute() const
  3008. {
  3009. return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute();
  3010. }
  3011. PUGI__FN xml_attribute xml_attribute::previous_attribute() const
  3012. {
  3013. return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute();
  3014. }
  3015. PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const
  3016. {
  3017. return (_attr && _attr->value) ? _attr->value : def;
  3018. }
  3019. PUGI__FN int xml_attribute::as_int(int def) const
  3020. {
  3021. return impl::get_value_int(_attr ? _attr->value : 0, def);
  3022. }
  3023. PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const
  3024. {
  3025. return impl::get_value_uint(_attr ? _attr->value : 0, def);
  3026. }
  3027. PUGI__FN double xml_attribute::as_double(double def) const
  3028. {
  3029. return impl::get_value_double(_attr ? _attr->value : 0, def);
  3030. }
  3031. PUGI__FN float xml_attribute::as_float(float def) const
  3032. {
  3033. return impl::get_value_float(_attr ? _attr->value : 0, def);
  3034. }
  3035. PUGI__FN bool xml_attribute::as_bool(bool def) const
  3036. {
  3037. return impl::get_value_bool(_attr ? _attr->value : 0, def);
  3038. }
  3039. PUGI__FN bool xml_attribute::empty() const
  3040. {
  3041. return !_attr;
  3042. }
  3043. PUGI__FN const char_t* xml_attribute::name() const
  3044. {
  3045. return (_attr && _attr->name) ? _attr->name : PUGIXML_TEXT("");
  3046. }
  3047. PUGI__FN const char_t* xml_attribute::value() const
  3048. {
  3049. return (_attr && _attr->value) ? _attr->value : PUGIXML_TEXT("");
  3050. }
  3051. PUGI__FN size_t xml_attribute::hash_value() const
  3052. {
  3053. return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct));
  3054. }
  3055. PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const
  3056. {
  3057. return _attr;
  3058. }
  3059. PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs)
  3060. {
  3061. set_value(rhs);
  3062. return *this;
  3063. }
  3064. PUGI__FN xml_attribute& xml_attribute::operator=(int rhs)
  3065. {
  3066. set_value(rhs);
  3067. return *this;
  3068. }
  3069. PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs)
  3070. {
  3071. set_value(rhs);
  3072. return *this;
  3073. }
  3074. PUGI__FN xml_attribute& xml_attribute::operator=(double rhs)
  3075. {
  3076. set_value(rhs);
  3077. return *this;
  3078. }
  3079. PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs)
  3080. {
  3081. set_value(rhs);
  3082. return *this;
  3083. }
  3084. PUGI__FN bool xml_attribute::set_name(const char_t* rhs)
  3085. {
  3086. if (!_attr) return false;
  3087. return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs);
  3088. }
  3089. PUGI__FN bool xml_attribute::set_value(const char_t* rhs)
  3090. {
  3091. if (!_attr) return false;
  3092. return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3093. }
  3094. PUGI__FN bool xml_attribute::set_value(int rhs)
  3095. {
  3096. if (!_attr) return false;
  3097. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3098. }
  3099. PUGI__FN bool xml_attribute::set_value(unsigned int rhs)
  3100. {
  3101. if (!_attr) return false;
  3102. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3103. }
  3104. PUGI__FN bool xml_attribute::set_value(double rhs)
  3105. {
  3106. if (!_attr) return false;
  3107. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3108. }
  3109. PUGI__FN bool xml_attribute::set_value(bool rhs)
  3110. {
  3111. if (!_attr) return false;
  3112. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3113. }
  3114. #ifdef __BORLANDC__
  3115. PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs)
  3116. {
  3117. return (bool)lhs && rhs;
  3118. }
  3119. PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs)
  3120. {
  3121. return (bool)lhs || rhs;
  3122. }
  3123. #endif
  3124. PUGI__FN xml_node::xml_node(): _root(0)
  3125. {
  3126. }
  3127. PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p)
  3128. {
  3129. }
  3130. PUGI__FN static void unspecified_bool_xml_node(xml_node***)
  3131. {
  3132. }
  3133. PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const
  3134. {
  3135. return _root ? unspecified_bool_xml_node : 0;
  3136. }
  3137. PUGI__FN bool xml_node::operator!() const
  3138. {
  3139. return !_root;
  3140. }
  3141. PUGI__FN xml_node::iterator xml_node::begin() const
  3142. {
  3143. return iterator(_root ? _root->first_child : 0, _root);
  3144. }
  3145. PUGI__FN xml_node::iterator xml_node::end() const
  3146. {
  3147. return iterator(0, _root);
  3148. }
  3149. PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const
  3150. {
  3151. return attribute_iterator(_root ? _root->first_attribute : 0, _root);
  3152. }
  3153. PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const
  3154. {
  3155. return attribute_iterator(0, _root);
  3156. }
  3157. PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const
  3158. {
  3159. return xml_object_range<xml_node_iterator>(begin(), end());
  3160. }
  3161. PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const
  3162. {
  3163. return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_), name_), xml_named_node_iterator());
  3164. }
  3165. PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const
  3166. {
  3167. return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end());
  3168. }
  3169. PUGI__FN bool xml_node::operator==(const xml_node& r) const
  3170. {
  3171. return (_root == r._root);
  3172. }
  3173. PUGI__FN bool xml_node::operator!=(const xml_node& r) const
  3174. {
  3175. return (_root != r._root);
  3176. }
  3177. PUGI__FN bool xml_node::operator<(const xml_node& r) const
  3178. {
  3179. return (_root < r._root);
  3180. }
  3181. PUGI__FN bool xml_node::operator>(const xml_node& r) const
  3182. {
  3183. return (_root > r._root);
  3184. }
  3185. PUGI__FN bool xml_node::operator<=(const xml_node& r) const
  3186. {
  3187. return (_root <= r._root);
  3188. }
  3189. PUGI__FN bool xml_node::operator>=(const xml_node& r) const
  3190. {
  3191. return (_root >= r._root);
  3192. }
  3193. PUGI__FN bool xml_node::empty() const
  3194. {
  3195. return !_root;
  3196. }
  3197. PUGI__FN const char_t* xml_node::name() const
  3198. {
  3199. return (_root && _root->name) ? _root->name : PUGIXML_TEXT("");
  3200. }
  3201. PUGI__FN xml_node_type xml_node::type() const
  3202. {
  3203. return _root ? static_cast<xml_node_type>((_root->header & impl::xml_memory_page_type_mask) + 1) : node_null;
  3204. }
  3205. PUGI__FN const char_t* xml_node::value() const
  3206. {
  3207. return (_root && _root->value) ? _root->value : PUGIXML_TEXT("");
  3208. }
  3209. PUGI__FN xml_node xml_node::child(const char_t* name_) const
  3210. {
  3211. if (!_root) return xml_node();
  3212. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  3213. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  3214. return xml_node();
  3215. }
  3216. PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const
  3217. {
  3218. if (!_root) return xml_attribute();
  3219. for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute)
  3220. if (i->name && impl::strequal(name_, i->name))
  3221. return xml_attribute(i);
  3222. return xml_attribute();
  3223. }
  3224. PUGI__FN xml_node xml_node::next_sibling(const char_t* name_) const
  3225. {
  3226. if (!_root) return xml_node();
  3227. for (xml_node_struct* i = _root->next_sibling; i; i = i->next_sibling)
  3228. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  3229. return xml_node();
  3230. }
  3231. PUGI__FN xml_node xml_node::next_sibling() const
  3232. {
  3233. if (!_root) return xml_node();
  3234. if (_root->next_sibling) return xml_node(_root->next_sibling);
  3235. else return xml_node();
  3236. }
  3237. PUGI__FN xml_node xml_node::previous_sibling(const char_t* name_) const
  3238. {
  3239. if (!_root) return xml_node();
  3240. for (xml_node_struct* i = _root->prev_sibling_c; i->next_sibling; i = i->prev_sibling_c)
  3241. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  3242. return xml_node();
  3243. }
  3244. PUGI__FN xml_node xml_node::previous_sibling() const
  3245. {
  3246. if (!_root) return xml_node();
  3247. if (_root->prev_sibling_c->next_sibling) return xml_node(_root->prev_sibling_c);
  3248. else return xml_node();
  3249. }
  3250. PUGI__FN xml_node xml_node::parent() const
  3251. {
  3252. return _root ? xml_node(_root->parent) : xml_node();
  3253. }
  3254. PUGI__FN xml_node xml_node::root() const
  3255. {
  3256. if (!_root) return xml_node();
  3257. impl::xml_memory_page* page = reinterpret_cast<impl::xml_memory_page*>(_root->header & impl::xml_memory_page_pointer_mask);
  3258. return xml_node(static_cast<impl::xml_document_struct*>(page->allocator));
  3259. }
  3260. PUGI__FN xml_text xml_node::text() const
  3261. {
  3262. return xml_text(_root);
  3263. }
  3264. PUGI__FN const char_t* xml_node::child_value() const
  3265. {
  3266. if (!_root) return PUGIXML_TEXT("");
  3267. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  3268. if (i->value && impl::is_text_node(i))
  3269. return i->value;
  3270. return PUGIXML_TEXT("");
  3271. }
  3272. PUGI__FN const char_t* xml_node::child_value(const char_t* name_) const
  3273. {
  3274. return child(name_).child_value();
  3275. }
  3276. PUGI__FN xml_attribute xml_node::first_attribute() const
  3277. {
  3278. return _root ? xml_attribute(_root->first_attribute) : xml_attribute();
  3279. }
  3280. PUGI__FN xml_attribute xml_node::last_attribute() const
  3281. {
  3282. return _root && _root->first_attribute ? xml_attribute(_root->first_attribute->prev_attribute_c) : xml_attribute();
  3283. }
  3284. PUGI__FN xml_node xml_node::first_child() const
  3285. {
  3286. return _root ? xml_node(_root->first_child) : xml_node();
  3287. }
  3288. PUGI__FN xml_node xml_node::last_child() const
  3289. {
  3290. return _root && _root->first_child ? xml_node(_root->first_child->prev_sibling_c) : xml_node();
  3291. }
  3292. PUGI__FN bool xml_node::set_name(const char_t* rhs)
  3293. {
  3294. switch (type())
  3295. {
  3296. case node_pi:
  3297. case node_declaration:
  3298. case node_element:
  3299. return impl::strcpy_insitu(_root->name, _root->header, impl::xml_memory_page_name_allocated_mask, rhs);
  3300. default:
  3301. return false;
  3302. }
  3303. }
  3304. PUGI__FN bool xml_node::set_value(const char_t* rhs)
  3305. {
  3306. switch (type())
  3307. {
  3308. case node_pi:
  3309. case node_cdata:
  3310. case node_pcdata:
  3311. case node_comment:
  3312. case node_doctype:
  3313. return impl::strcpy_insitu(_root->value, _root->header, impl::xml_memory_page_value_allocated_mask, rhs);
  3314. default:
  3315. return false;
  3316. }
  3317. }
  3318. PUGI__FN xml_attribute xml_node::append_attribute(const char_t* name_)
  3319. {
  3320. if (type() != node_element && type() != node_declaration) return xml_attribute();
  3321. xml_attribute a(impl::append_attribute_ll(_root, impl::get_allocator(_root)));
  3322. a.set_name(name_);
  3323. return a;
  3324. }
  3325. PUGI__FN xml_attribute xml_node::prepend_attribute(const char_t* name_)
  3326. {
  3327. if (type() != node_element && type() != node_declaration) return xml_attribute();
  3328. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3329. if (!a) return xml_attribute();
  3330. a.set_name(name_);
  3331. xml_attribute_struct* head = _root->first_attribute;
  3332. if (head)
  3333. {
  3334. a._attr->prev_attribute_c = head->prev_attribute_c;
  3335. head->prev_attribute_c = a._attr;
  3336. }
  3337. else
  3338. a._attr->prev_attribute_c = a._attr;
  3339. a._attr->next_attribute = head;
  3340. _root->first_attribute = a._attr;
  3341. return a;
  3342. }
  3343. PUGI__FN xml_attribute xml_node::insert_attribute_before(const char_t* name_, const xml_attribute& attr)
  3344. {
  3345. if ((type() != node_element && type() != node_declaration) || attr.empty()) return xml_attribute();
  3346. // check that attribute belongs to *this
  3347. xml_attribute_struct* cur = attr._attr;
  3348. while (cur->prev_attribute_c->next_attribute) cur = cur->prev_attribute_c;
  3349. if (cur != _root->first_attribute) return xml_attribute();
  3350. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3351. if (!a) return xml_attribute();
  3352. a.set_name(name_);
  3353. if (attr._attr->prev_attribute_c->next_attribute)
  3354. attr._attr->prev_attribute_c->next_attribute = a._attr;
  3355. else
  3356. _root->first_attribute = a._attr;
  3357. a._attr->prev_attribute_c = attr._attr->prev_attribute_c;
  3358. a._attr->next_attribute = attr._attr;
  3359. attr._attr->prev_attribute_c = a._attr;
  3360. return a;
  3361. }
  3362. PUGI__FN xml_attribute xml_node::insert_attribute_after(const char_t* name_, const xml_attribute& attr)
  3363. {
  3364. if ((type() != node_element && type() != node_declaration) || attr.empty()) return xml_attribute();
  3365. // check that attribute belongs to *this
  3366. xml_attribute_struct* cur = attr._attr;
  3367. while (cur->prev_attribute_c->next_attribute) cur = cur->prev_attribute_c;
  3368. if (cur != _root->first_attribute) return xml_attribute();
  3369. xml_attribute a(impl::allocate_attribute(impl::get_allocator(_root)));
  3370. if (!a) return xml_attribute();
  3371. a.set_name(name_);
  3372. if (attr._attr->next_attribute)
  3373. attr._attr->next_attribute->prev_attribute_c = a._attr;
  3374. else
  3375. _root->first_attribute->prev_attribute_c = a._attr;
  3376. a._attr->next_attribute = attr._attr->next_attribute;
  3377. a._attr->prev_attribute_c = attr._attr;
  3378. attr._attr->next_attribute = a._attr;
  3379. return a;
  3380. }
  3381. PUGI__FN xml_attribute xml_node::append_copy(const xml_attribute& proto)
  3382. {
  3383. if (!proto) return xml_attribute();
  3384. xml_attribute result = append_attribute(proto.name());
  3385. result.set_value(proto.value());
  3386. return result;
  3387. }
  3388. PUGI__FN xml_attribute xml_node::prepend_copy(const xml_attribute& proto)
  3389. {
  3390. if (!proto) return xml_attribute();
  3391. xml_attribute result = prepend_attribute(proto.name());
  3392. result.set_value(proto.value());
  3393. return result;
  3394. }
  3395. PUGI__FN xml_attribute xml_node::insert_copy_after(const xml_attribute& proto, const xml_attribute& attr)
  3396. {
  3397. if (!proto) return xml_attribute();
  3398. xml_attribute result = insert_attribute_after(proto.name(), attr);
  3399. result.set_value(proto.value());
  3400. return result;
  3401. }
  3402. PUGI__FN xml_attribute xml_node::insert_copy_before(const xml_attribute& proto, const xml_attribute& attr)
  3403. {
  3404. if (!proto) return xml_attribute();
  3405. xml_attribute result = insert_attribute_before(proto.name(), attr);
  3406. result.set_value(proto.value());
  3407. return result;
  3408. }
  3409. PUGI__FN xml_node xml_node::append_child(xml_node_type type_)
  3410. {
  3411. if (!impl::allow_insert_child(this->type(), type_)) return xml_node();
  3412. xml_node n(impl::append_node(_root, impl::get_allocator(_root), type_));
  3413. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3414. return n;
  3415. }
  3416. PUGI__FN xml_node xml_node::prepend_child(xml_node_type type_)
  3417. {
  3418. if (!impl::allow_insert_child(this->type(), type_)) return xml_node();
  3419. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3420. if (!n) return xml_node();
  3421. n._root->parent = _root;
  3422. xml_node_struct* head = _root->first_child;
  3423. if (head)
  3424. {
  3425. n._root->prev_sibling_c = head->prev_sibling_c;
  3426. head->prev_sibling_c = n._root;
  3427. }
  3428. else
  3429. n._root->prev_sibling_c = n._root;
  3430. n._root->next_sibling = head;
  3431. _root->first_child = n._root;
  3432. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3433. return n;
  3434. }
  3435. PUGI__FN xml_node xml_node::insert_child_before(xml_node_type type_, const xml_node& node)
  3436. {
  3437. if (!impl::allow_insert_child(this->type(), type_)) return xml_node();
  3438. if (!node._root || node._root->parent != _root) return xml_node();
  3439. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3440. if (!n) return xml_node();
  3441. n._root->parent = _root;
  3442. if (node._root->prev_sibling_c->next_sibling)
  3443. node._root->prev_sibling_c->next_sibling = n._root;
  3444. else
  3445. _root->first_child = n._root;
  3446. n._root->prev_sibling_c = node._root->prev_sibling_c;
  3447. n._root->next_sibling = node._root;
  3448. node._root->prev_sibling_c = n._root;
  3449. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3450. return n;
  3451. }
  3452. PUGI__FN xml_node xml_node::insert_child_after(xml_node_type type_, const xml_node& node)
  3453. {
  3454. if (!impl::allow_insert_child(this->type(), type_)) return xml_node();
  3455. if (!node._root || node._root->parent != _root) return xml_node();
  3456. xml_node n(impl::allocate_node(impl::get_allocator(_root), type_));
  3457. if (!n) return xml_node();
  3458. n._root->parent = _root;
  3459. if (node._root->next_sibling)
  3460. node._root->next_sibling->prev_sibling_c = n._root;
  3461. else
  3462. _root->first_child->prev_sibling_c = n._root;
  3463. n._root->next_sibling = node._root->next_sibling;
  3464. n._root->prev_sibling_c = node._root;
  3465. node._root->next_sibling = n._root;
  3466. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  3467. return n;
  3468. }
  3469. PUGI__FN xml_node xml_node::append_child(const char_t* name_)
  3470. {
  3471. xml_node result = append_child(node_element);
  3472. result.set_name(name_);
  3473. return result;
  3474. }
  3475. PUGI__FN xml_node xml_node::prepend_child(const char_t* name_)
  3476. {
  3477. xml_node result = prepend_child(node_element);
  3478. result.set_name(name_);
  3479. return result;
  3480. }
  3481. PUGI__FN xml_node xml_node::insert_child_after(const char_t* name_, const xml_node& node)
  3482. {
  3483. xml_node result = insert_child_after(node_element, node);
  3484. result.set_name(name_);
  3485. return result;
  3486. }
  3487. PUGI__FN xml_node xml_node::insert_child_before(const char_t* name_, const xml_node& node)
  3488. {
  3489. xml_node result = insert_child_before(node_element, node);
  3490. result.set_name(name_);
  3491. return result;
  3492. }
  3493. PUGI__FN xml_node xml_node::append_copy(const xml_node& proto)
  3494. {
  3495. xml_node result = append_child(proto.type());
  3496. if (result) impl::recursive_copy_skip(result, proto, result);
  3497. return result;
  3498. }
  3499. PUGI__FN xml_node xml_node::prepend_copy(const xml_node& proto)
  3500. {
  3501. xml_node result = prepend_child(proto.type());
  3502. if (result) impl::recursive_copy_skip(result, proto, result);
  3503. return result;
  3504. }
  3505. PUGI__FN xml_node xml_node::insert_copy_after(const xml_node& proto, const xml_node& node)
  3506. {
  3507. xml_node result = insert_child_after(proto.type(), node);
  3508. if (result) impl::recursive_copy_skip(result, proto, result);
  3509. return result;
  3510. }
  3511. PUGI__FN xml_node xml_node::insert_copy_before(const xml_node& proto, const xml_node& node)
  3512. {
  3513. xml_node result = insert_child_before(proto.type(), node);
  3514. if (result) impl::recursive_copy_skip(result, proto, result);
  3515. return result;
  3516. }
  3517. PUGI__FN bool xml_node::remove_attribute(const char_t* name_)
  3518. {
  3519. return remove_attribute(attribute(name_));
  3520. }
  3521. PUGI__FN bool xml_node::remove_attribute(const xml_attribute& a)
  3522. {
  3523. if (!_root || !a._attr) return false;
  3524. // check that attribute belongs to *this
  3525. xml_attribute_struct* attr = a._attr;
  3526. while (attr->prev_attribute_c->next_attribute) attr = attr->prev_attribute_c;
  3527. if (attr != _root->first_attribute) return false;
  3528. if (a._attr->next_attribute) a._attr->next_attribute->prev_attribute_c = a._attr->prev_attribute_c;
  3529. else if (_root->first_attribute) _root->first_attribute->prev_attribute_c = a._attr->prev_attribute_c;
  3530. if (a._attr->prev_attribute_c->next_attribute) a._attr->prev_attribute_c->next_attribute = a._attr->next_attribute;
  3531. else _root->first_attribute = a._attr->next_attribute;
  3532. impl::destroy_attribute(a._attr, impl::get_allocator(_root));
  3533. return true;
  3534. }
  3535. PUGI__FN bool xml_node::remove_child(const char_t* name_)
  3536. {
  3537. return remove_child(child(name_));
  3538. }
  3539. PUGI__FN bool xml_node::remove_child(const xml_node& n)
  3540. {
  3541. if (!_root || !n._root || n._root->parent != _root) return false;
  3542. if (n._root->next_sibling) n._root->next_sibling->prev_sibling_c = n._root->prev_sibling_c;
  3543. else if (_root->first_child) _root->first_child->prev_sibling_c = n._root->prev_sibling_c;
  3544. if (n._root->prev_sibling_c->next_sibling) n._root->prev_sibling_c->next_sibling = n._root->next_sibling;
  3545. else _root->first_child = n._root->next_sibling;
  3546. impl::destroy_node(n._root, impl::get_allocator(_root));
  3547. return true;
  3548. }
  3549. PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* name_, const char_t* attr_name, const char_t* attr_value) const
  3550. {
  3551. if (!_root) return xml_node();
  3552. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  3553. if (i->name && impl::strequal(name_, i->name))
  3554. {
  3555. for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
  3556. if (impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value))
  3557. return xml_node(i);
  3558. }
  3559. return xml_node();
  3560. }
  3561. PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const
  3562. {
  3563. if (!_root) return xml_node();
  3564. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  3565. for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
  3566. if (impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value))
  3567. return xml_node(i);
  3568. return xml_node();
  3569. }
  3570. #ifndef PUGIXML_NO_STL
  3571. PUGI__FN string_t xml_node::path(char_t delimiter) const
  3572. {
  3573. xml_node cursor = *this; // Make a copy.
  3574. string_t result = cursor.name();
  3575. while (cursor.parent())
  3576. {
  3577. cursor = cursor.parent();
  3578. string_t temp = cursor.name();
  3579. temp += delimiter;
  3580. temp += result;
  3581. result.swap(temp);
  3582. }
  3583. return result;
  3584. }
  3585. #endif
  3586. PUGI__FN xml_node xml_node::first_element_by_path(const char_t* path_, char_t delimiter) const
  3587. {
  3588. xml_node found = *this; // Current search context.
  3589. if (!_root || !path_ || !path_[0]) return found;
  3590. if (path_[0] == delimiter)
  3591. {
  3592. // Absolute path; e.g. '/foo/bar'
  3593. found = found.root();
  3594. ++path_;
  3595. }
  3596. const char_t* path_segment = path_;
  3597. while (*path_segment == delimiter) ++path_segment;
  3598. const char_t* path_segment_end = path_segment;
  3599. while (*path_segment_end && *path_segment_end != delimiter) ++path_segment_end;
  3600. if (path_segment == path_segment_end) return found;
  3601. const char_t* next_segment = path_segment_end;
  3602. while (*next_segment == delimiter) ++next_segment;
  3603. if (*path_segment == '.' && path_segment + 1 == path_segment_end)
  3604. return found.first_element_by_path(next_segment, delimiter);
  3605. else if (*path_segment == '.' && *(path_segment+1) == '.' && path_segment + 2 == path_segment_end)
  3606. return found.parent().first_element_by_path(next_segment, delimiter);
  3607. else
  3608. {
  3609. for (xml_node_struct* j = found._root->first_child; j; j = j->next_sibling)
  3610. {
  3611. if (j->name && impl::strequalrange(j->name, path_segment, static_cast<size_t>(path_segment_end - path_segment)))
  3612. {
  3613. xml_node subsearch = xml_node(j).first_element_by_path(next_segment, delimiter);
  3614. if (subsearch) return subsearch;
  3615. }
  3616. }
  3617. return xml_node();
  3618. }
  3619. }
  3620. PUGI__FN bool xml_node::traverse(xml_tree_walker& walker)
  3621. {
  3622. walker._depth = -1;
  3623. xml_node arg_begin = *this;
  3624. if (!walker.begin(arg_begin)) return false;
  3625. xml_node cur = first_child();
  3626. if (cur)
  3627. {
  3628. ++walker._depth;
  3629. do
  3630. {
  3631. xml_node arg_for_each = cur;
  3632. if (!walker.for_each(arg_for_each))
  3633. return false;
  3634. if (cur.first_child())
  3635. {
  3636. ++walker._depth;
  3637. cur = cur.first_child();
  3638. }
  3639. else if (cur.next_sibling())
  3640. cur = cur.next_sibling();
  3641. else
  3642. {
  3643. // Borland C++ workaround
  3644. while (!cur.next_sibling() && cur != *this && !cur.parent().empty())
  3645. {
  3646. --walker._depth;
  3647. cur = cur.parent();
  3648. }
  3649. if (cur != *this)
  3650. cur = cur.next_sibling();
  3651. }
  3652. }
  3653. while (cur && cur != *this);
  3654. }
  3655. assert(walker._depth == -1);
  3656. xml_node arg_end = *this;
  3657. return walker.end(arg_end);
  3658. }
  3659. PUGI__FN size_t xml_node::hash_value() const
  3660. {
  3661. return static_cast<size_t>(reinterpret_cast<uintptr_t>(_root) / sizeof(xml_node_struct));
  3662. }
  3663. PUGI__FN xml_node_struct* xml_node::internal_object() const
  3664. {
  3665. return _root;
  3666. }
  3667. PUGI__FN void xml_node::print(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
  3668. {
  3669. if (!_root) return;
  3670. impl::xml_buffered_writer buffered_writer(writer, encoding);
  3671. impl::node_output(buffered_writer, *this, indent, flags, depth);
  3672. }
  3673. #ifndef PUGIXML_NO_STL
  3674. PUGI__FN void xml_node::print(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
  3675. {
  3676. xml_writer_stream writer(stream);
  3677. print(writer, indent, flags, encoding, depth);
  3678. }
  3679. PUGI__FN void xml_node::print(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags, unsigned int depth) const
  3680. {
  3681. xml_writer_stream writer(stream);
  3682. print(writer, indent, flags, encoding_wchar, depth);
  3683. }
  3684. #endif
  3685. PUGI__FN ptrdiff_t xml_node::offset_debug() const
  3686. {
  3687. xml_node_struct* r = root()._root;
  3688. if (!r) return -1;
  3689. const char_t* buffer = static_cast<impl::xml_document_struct*>(r)->buffer;
  3690. if (!buffer) return -1;
  3691. switch (type())
  3692. {
  3693. case node_document:
  3694. return 0;
  3695. case node_element:
  3696. case node_declaration:
  3697. case node_pi:
  3698. return (_root->header & impl::xml_memory_page_name_allocated_mask) ? -1 : _root->name - buffer;
  3699. case node_pcdata:
  3700. case node_cdata:
  3701. case node_comment:
  3702. case node_doctype:
  3703. return (_root->header & impl::xml_memory_page_value_allocated_mask) ? -1 : _root->value - buffer;
  3704. default:
  3705. return -1;
  3706. }
  3707. }
  3708. #ifdef __BORLANDC__
  3709. PUGI__FN bool operator&&(const xml_node& lhs, bool rhs)
  3710. {
  3711. return (bool)lhs && rhs;
  3712. }
  3713. PUGI__FN bool operator||(const xml_node& lhs, bool rhs)
  3714. {
  3715. return (bool)lhs || rhs;
  3716. }
  3717. #endif
  3718. PUGI__FN xml_text::xml_text(xml_node_struct* root): _root(root)
  3719. {
  3720. }
  3721. PUGI__FN xml_node_struct* xml_text::_data() const
  3722. {
  3723. if (!_root || impl::is_text_node(_root)) return _root;
  3724. for (xml_node_struct* node = _root->first_child; node; node = node->next_sibling)
  3725. if (impl::is_text_node(node))
  3726. return node;
  3727. return 0;
  3728. }
  3729. PUGI__FN xml_node_struct* xml_text::_data_new()
  3730. {
  3731. xml_node_struct* d = _data();
  3732. if (d) return d;
  3733. return xml_node(_root).append_child(node_pcdata).internal_object();
  3734. }
  3735. PUGI__FN xml_text::xml_text(): _root(0)
  3736. {
  3737. }
  3738. PUGI__FN static void unspecified_bool_xml_text(xml_text***)
  3739. {
  3740. }
  3741. PUGI__FN xml_text::operator xml_text::unspecified_bool_type() const
  3742. {
  3743. return _data() ? unspecified_bool_xml_text : 0;
  3744. }
  3745. PUGI__FN bool xml_text::operator!() const
  3746. {
  3747. return !_data();
  3748. }
  3749. PUGI__FN bool xml_text::empty() const
  3750. {
  3751. return _data() == 0;
  3752. }
  3753. PUGI__FN const char_t* xml_text::get() const
  3754. {
  3755. xml_node_struct* d = _data();
  3756. return (d && d->value) ? d->value : PUGIXML_TEXT("");
  3757. }
  3758. PUGI__FN const char_t* xml_text::as_string(const char_t* def) const
  3759. {
  3760. xml_node_struct* d = _data();
  3761. return (d && d->value) ? d->value : def;
  3762. }
  3763. PUGI__FN int xml_text::as_int(int def) const
  3764. {
  3765. xml_node_struct* d = _data();
  3766. return impl::get_value_int(d ? d->value : 0, def);
  3767. }
  3768. PUGI__FN unsigned int xml_text::as_uint(unsigned int def) const
  3769. {
  3770. xml_node_struct* d = _data();
  3771. return impl::get_value_uint(d ? d->value : 0, def);
  3772. }
  3773. PUGI__FN double xml_text::as_double(double def) const
  3774. {
  3775. xml_node_struct* d = _data();
  3776. return impl::get_value_double(d ? d->value : 0, def);
  3777. }
  3778. PUGI__FN float xml_text::as_float(float def) const
  3779. {
  3780. xml_node_struct* d = _data();
  3781. return impl::get_value_float(d ? d->value : 0, def);
  3782. }
  3783. PUGI__FN bool xml_text::as_bool(bool def) const
  3784. {
  3785. xml_node_struct* d = _data();
  3786. return impl::get_value_bool(d ? d->value : 0, def);
  3787. }
  3788. PUGI__FN bool xml_text::set(const char_t* rhs)
  3789. {
  3790. xml_node_struct* dn = _data_new();
  3791. return dn ? impl::strcpy_insitu(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  3792. }
  3793. PUGI__FN bool xml_text::set(int rhs)
  3794. {
  3795. xml_node_struct* dn = _data_new();
  3796. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  3797. }
  3798. PUGI__FN bool xml_text::set(unsigned int rhs)
  3799. {
  3800. xml_node_struct* dn = _data_new();
  3801. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  3802. }
  3803. PUGI__FN bool xml_text::set(double rhs)
  3804. {
  3805. xml_node_struct* dn = _data_new();
  3806. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  3807. }
  3808. PUGI__FN bool xml_text::set(bool rhs)
  3809. {
  3810. xml_node_struct* dn = _data_new();
  3811. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  3812. }
  3813. PUGI__FN xml_text& xml_text::operator=(const char_t* rhs)
  3814. {
  3815. set(rhs);
  3816. return *this;
  3817. }
  3818. PUGI__FN xml_text& xml_text::operator=(int rhs)
  3819. {
  3820. set(rhs);
  3821. return *this;
  3822. }
  3823. PUGI__FN xml_text& xml_text::operator=(unsigned int rhs)
  3824. {
  3825. set(rhs);
  3826. return *this;
  3827. }
  3828. PUGI__FN xml_text& xml_text::operator=(double rhs)
  3829. {
  3830. set(rhs);
  3831. return *this;
  3832. }
  3833. PUGI__FN xml_text& xml_text::operator=(bool rhs)
  3834. {
  3835. set(rhs);
  3836. return *this;
  3837. }
  3838. PUGI__FN xml_node xml_text::data() const
  3839. {
  3840. return xml_node(_data());
  3841. }
  3842. #ifdef __BORLANDC__
  3843. PUGI__FN bool operator&&(const xml_text& lhs, bool rhs)
  3844. {
  3845. return (bool)lhs && rhs;
  3846. }
  3847. PUGI__FN bool operator||(const xml_text& lhs, bool rhs)
  3848. {
  3849. return (bool)lhs || rhs;
  3850. }
  3851. #endif
  3852. PUGI__FN xml_node_iterator::xml_node_iterator()
  3853. {
  3854. }
  3855. PUGI__FN xml_node_iterator::xml_node_iterator(const xml_node& node): _wrap(node), _parent(node.parent())
  3856. {
  3857. }
  3858. PUGI__FN xml_node_iterator::xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
  3859. {
  3860. }
  3861. PUGI__FN bool xml_node_iterator::operator==(const xml_node_iterator& rhs) const
  3862. {
  3863. return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
  3864. }
  3865. PUGI__FN bool xml_node_iterator::operator!=(const xml_node_iterator& rhs) const
  3866. {
  3867. return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
  3868. }
  3869. PUGI__FN xml_node& xml_node_iterator::operator*() const
  3870. {
  3871. assert(_wrap._root);
  3872. return _wrap;
  3873. }
  3874. PUGI__FN xml_node* xml_node_iterator::operator->() const
  3875. {
  3876. assert(_wrap._root);
  3877. return const_cast<xml_node*>(&_wrap); // BCC32 workaround
  3878. }
  3879. PUGI__FN const xml_node_iterator& xml_node_iterator::operator++()
  3880. {
  3881. assert(_wrap._root);
  3882. _wrap._root = _wrap._root->next_sibling;
  3883. return *this;
  3884. }
  3885. PUGI__FN xml_node_iterator xml_node_iterator::operator++(int)
  3886. {
  3887. xml_node_iterator temp = *this;
  3888. ++*this;
  3889. return temp;
  3890. }
  3891. PUGI__FN const xml_node_iterator& xml_node_iterator::operator--()
  3892. {
  3893. _wrap = _wrap._root ? _wrap.previous_sibling() : _parent.last_child();
  3894. return *this;
  3895. }
  3896. PUGI__FN xml_node_iterator xml_node_iterator::operator--(int)
  3897. {
  3898. xml_node_iterator temp = *this;
  3899. --*this;
  3900. return temp;
  3901. }
  3902. PUGI__FN xml_attribute_iterator::xml_attribute_iterator()
  3903. {
  3904. }
  3905. PUGI__FN xml_attribute_iterator::xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent): _wrap(attr), _parent(parent)
  3906. {
  3907. }
  3908. PUGI__FN xml_attribute_iterator::xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
  3909. {
  3910. }
  3911. PUGI__FN bool xml_attribute_iterator::operator==(const xml_attribute_iterator& rhs) const
  3912. {
  3913. return _wrap._attr == rhs._wrap._attr && _parent._root == rhs._parent._root;
  3914. }
  3915. PUGI__FN bool xml_attribute_iterator::operator!=(const xml_attribute_iterator& rhs) const
  3916. {
  3917. return _wrap._attr != rhs._wrap._attr || _parent._root != rhs._parent._root;
  3918. }
  3919. PUGI__FN xml_attribute& xml_attribute_iterator::operator*() const
  3920. {
  3921. assert(_wrap._attr);
  3922. return _wrap;
  3923. }
  3924. PUGI__FN xml_attribute* xml_attribute_iterator::operator->() const
  3925. {
  3926. assert(_wrap._attr);
  3927. return const_cast<xml_attribute*>(&_wrap); // BCC32 workaround
  3928. }
  3929. PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator++()
  3930. {
  3931. assert(_wrap._attr);
  3932. _wrap._attr = _wrap._attr->next_attribute;
  3933. return *this;
  3934. }
  3935. PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator++(int)
  3936. {
  3937. xml_attribute_iterator temp = *this;
  3938. ++*this;
  3939. return temp;
  3940. }
  3941. PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator--()
  3942. {
  3943. _wrap = _wrap._attr ? _wrap.previous_attribute() : _parent.last_attribute();
  3944. return *this;
  3945. }
  3946. PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator--(int)
  3947. {
  3948. xml_attribute_iterator temp = *this;
  3949. --*this;
  3950. return temp;
  3951. }
  3952. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(): _name(0)
  3953. {
  3954. }
  3955. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(const xml_node& node, const char_t* name): _node(node), _name(name)
  3956. {
  3957. }
  3958. PUGI__FN bool xml_named_node_iterator::operator==(const xml_named_node_iterator& rhs) const
  3959. {
  3960. return _node == rhs._node;
  3961. }
  3962. PUGI__FN bool xml_named_node_iterator::operator!=(const xml_named_node_iterator& rhs) const
  3963. {
  3964. return _node != rhs._node;
  3965. }
  3966. PUGI__FN xml_node& xml_named_node_iterator::operator*() const
  3967. {
  3968. assert(_node._root);
  3969. return _node;
  3970. }
  3971. PUGI__FN xml_node* xml_named_node_iterator::operator->() const
  3972. {
  3973. assert(_node._root);
  3974. return const_cast<xml_node*>(&_node); // BCC32 workaround
  3975. }
  3976. PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator++()
  3977. {
  3978. assert(_node._root);
  3979. _node = _node.next_sibling(_name);
  3980. return *this;
  3981. }
  3982. PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator++(int)
  3983. {
  3984. xml_named_node_iterator temp = *this;
  3985. ++*this;
  3986. return temp;
  3987. }
  3988. PUGI__FN xml_parse_result::xml_parse_result(): status(status_internal_error), offset(0), encoding(encoding_auto)
  3989. {
  3990. }
  3991. PUGI__FN xml_parse_result::operator bool() const
  3992. {
  3993. return status == status_ok;
  3994. }
  3995. PUGI__FN const char* xml_parse_result::description() const
  3996. {
  3997. switch (status)
  3998. {
  3999. case status_ok: return "No error";
  4000. case status_file_not_found: return "File was not found";
  4001. case status_io_error: return "Error reading from file/stream";
  4002. case status_out_of_memory: return "Could not allocate memory";
  4003. case status_internal_error: return "Internal error occurred";
  4004. case status_unrecognized_tag: return "Could not determine tag type";
  4005. case status_bad_pi: return "Error parsing document declaration/processing instruction";
  4006. case status_bad_comment: return "Error parsing comment";
  4007. case status_bad_cdata: return "Error parsing CDATA section";
  4008. case status_bad_doctype: return "Error parsing document type declaration";
  4009. case status_bad_pcdata: return "Error parsing PCDATA section";
  4010. case status_bad_start_element: return "Error parsing start element tag";
  4011. case status_bad_attribute: return "Error parsing element attribute";
  4012. case status_bad_end_element: return "Error parsing end element tag";
  4013. case status_end_element_mismatch: return "Start-end tags mismatch";
  4014. default: return "Unknown error";
  4015. }
  4016. }
  4017. PUGI__FN xml_document::xml_document(): _buffer(0)
  4018. {
  4019. create();
  4020. }
  4021. PUGI__FN xml_document::~xml_document()
  4022. {
  4023. destroy();
  4024. }
  4025. PUGI__FN void xml_document::reset()
  4026. {
  4027. destroy();
  4028. create();
  4029. }
  4030. PUGI__FN void xml_document::reset(const xml_document& proto)
  4031. {
  4032. reset();
  4033. for (xml_node cur = proto.first_child(); cur; cur = cur.next_sibling())
  4034. append_copy(cur);
  4035. }
  4036. PUGI__FN void xml_document::create()
  4037. {
  4038. // initialize sentinel page
  4039. PUGI__STATIC_ASSERT(offsetof(impl::xml_memory_page, data) + sizeof(impl::xml_document_struct) + impl::xml_memory_page_alignment <= sizeof(_memory));
  4040. // align upwards to page boundary
  4041. void* page_memory = reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(_memory) + (impl::xml_memory_page_alignment - 1)) & ~(impl::xml_memory_page_alignment - 1));
  4042. // prepare page structure
  4043. impl::xml_memory_page* page = impl::xml_memory_page::construct(page_memory);
  4044. page->busy_size = impl::xml_memory_page_size;
  4045. // allocate new root
  4046. _root = new (page->data) impl::xml_document_struct(page);
  4047. _root->prev_sibling_c = _root;
  4048. // setup sentinel page
  4049. page->allocator = static_cast<impl::xml_document_struct*>(_root);
  4050. }
  4051. PUGI__FN void xml_document::destroy()
  4052. {
  4053. // destroy static storage
  4054. if (_buffer)
  4055. {
  4056. impl::xml_memory::deallocate(_buffer);
  4057. _buffer = 0;
  4058. }
  4059. // destroy dynamic storage, leave sentinel page (it's in static memory)
  4060. if (_root)
  4061. {
  4062. impl::xml_memory_page* root_page = reinterpret_cast<impl::xml_memory_page*>(_root->header & impl::xml_memory_page_pointer_mask);
  4063. assert(root_page && !root_page->prev && !root_page->memory);
  4064. // destroy all pages
  4065. for (impl::xml_memory_page* page = root_page->next; page; )
  4066. {
  4067. impl::xml_memory_page* next = page->next;
  4068. impl::xml_allocator::deallocate_page(page);
  4069. page = next;
  4070. }
  4071. // cleanup root page
  4072. root_page->allocator = 0;
  4073. root_page->next = 0;
  4074. root_page->busy_size = root_page->freed_size = 0;
  4075. _root = 0;
  4076. }
  4077. }
  4078. #ifndef PUGIXML_NO_STL
  4079. PUGI__FN xml_parse_result xml_document::load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options, xml_encoding encoding)
  4080. {
  4081. reset();
  4082. return impl::load_stream_impl(*this, stream, options, encoding);
  4083. }
  4084. PUGI__FN xml_parse_result xml_document::load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options)
  4085. {
  4086. reset();
  4087. return impl::load_stream_impl(*this, stream, options, encoding_wchar);
  4088. }
  4089. #endif
  4090. PUGI__FN xml_parse_result xml_document::load(const char_t* contents, unsigned int options)
  4091. {
  4092. // Force native encoding (skip autodetection)
  4093. #ifdef PUGIXML_WCHAR_MODE
  4094. xml_encoding encoding = encoding_wchar;
  4095. #else
  4096. xml_encoding encoding = encoding_utf8;
  4097. #endif
  4098. return load_buffer(contents, impl::strlength(contents) * sizeof(char_t), options, encoding);
  4099. }
  4100. PUGI__FN xml_parse_result xml_document::load_file(const char* path_, unsigned int options, xml_encoding encoding)
  4101. {
  4102. reset();
  4103. FILE* file = fopen(path_, "rb");
  4104. return impl::load_file_impl(*this, file, options, encoding);
  4105. }
  4106. PUGI__FN xml_parse_result xml_document::load_file(const wchar_t* path_, unsigned int options, xml_encoding encoding)
  4107. {
  4108. reset();
  4109. FILE* file = impl::open_file_wide(path_, L"rb");
  4110. return impl::load_file_impl(*this, file, options, encoding);
  4111. }
  4112. PUGI__FN xml_parse_result xml_document::load_buffer_impl(void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own)
  4113. {
  4114. reset();
  4115. // check input buffer
  4116. assert(contents || size == 0);
  4117. // get actual encoding
  4118. xml_encoding buffer_encoding = impl::get_buffer_encoding(encoding, contents, size);
  4119. // get private buffer
  4120. char_t* buffer = 0;
  4121. size_t length = 0;
  4122. if (!impl::convert_buffer(buffer, length, buffer_encoding, contents, size, is_mutable)) return impl::make_parse_result(status_out_of_memory);
  4123. // delete original buffer if we performed a conversion
  4124. if (own && buffer != contents && contents) impl::xml_memory::deallocate(contents);
  4125. // parse
  4126. xml_parse_result res = impl::xml_parser::parse(buffer, length, _root, options);
  4127. // remember encoding
  4128. res.encoding = buffer_encoding;
  4129. // grab onto buffer if it's our buffer, user is responsible for deallocating contens himself
  4130. if (own || buffer != contents) _buffer = buffer;
  4131. return res;
  4132. }
  4133. PUGI__FN xml_parse_result xml_document::load_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4134. {
  4135. return load_buffer_impl(const_cast<void*>(contents), size, options, encoding, false, false);
  4136. }
  4137. PUGI__FN xml_parse_result xml_document::load_buffer_inplace(void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4138. {
  4139. return load_buffer_impl(contents, size, options, encoding, true, false);
  4140. }
  4141. PUGI__FN xml_parse_result xml_document::load_buffer_inplace_own(void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4142. {
  4143. return load_buffer_impl(contents, size, options, encoding, true, true);
  4144. }
  4145. PUGI__FN void xml_document::save(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4146. {
  4147. impl::xml_buffered_writer buffered_writer(writer, encoding);
  4148. if ((flags & format_write_bom) && encoding != encoding_latin1)
  4149. {
  4150. // BOM always represents the codepoint U+FEFF, so just write it in native encoding
  4151. #ifdef PUGIXML_WCHAR_MODE
  4152. unsigned int bom = 0xfeff;
  4153. buffered_writer.write(static_cast<wchar_t>(bom));
  4154. #else
  4155. buffered_writer.write('\xef', '\xbb', '\xbf');
  4156. #endif
  4157. }
  4158. if (!(flags & format_no_declaration) && !impl::has_declaration(*this))
  4159. {
  4160. buffered_writer.write(PUGIXML_TEXT("<?xml version=\"1.0\""));
  4161. if (encoding == encoding_latin1) buffered_writer.write(PUGIXML_TEXT(" encoding=\"ISO-8859-1\""));
  4162. buffered_writer.write('?', '>');
  4163. if (!(flags & format_raw)) buffered_writer.write('\n');
  4164. }
  4165. impl::node_output(buffered_writer, *this, indent, flags, 0);
  4166. }
  4167. #ifndef PUGIXML_NO_STL
  4168. PUGI__FN void xml_document::save(std::basic_ostream<char, std::char_traits<char> >& stream, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4169. {
  4170. xml_writer_stream writer(stream);
  4171. save(writer, indent, flags, encoding);
  4172. }
  4173. PUGI__FN void xml_document::save(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream, const char_t* indent, unsigned int flags) const
  4174. {
  4175. xml_writer_stream writer(stream);
  4176. save(writer, indent, flags, encoding_wchar);
  4177. }
  4178. #endif
  4179. PUGI__FN bool xml_document::save_file(const char* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4180. {
  4181. FILE* file = fopen(path_, (flags & format_save_file_text) ? "w" : "wb");
  4182. return impl::save_file_impl(*this, file, indent, flags, encoding);
  4183. }
  4184. PUGI__FN bool xml_document::save_file(const wchar_t* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  4185. {
  4186. FILE* file = impl::open_file_wide(path_, (flags & format_save_file_text) ? L"w" : L"wb");
  4187. return impl::save_file_impl(*this, file, indent, flags, encoding);
  4188. }
  4189. PUGI__FN xml_node xml_document::document_element() const
  4190. {
  4191. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4192. if ((i->header & impl::xml_memory_page_type_mask) + 1 == node_element)
  4193. return xml_node(i);
  4194. return xml_node();
  4195. }
  4196. #ifndef PUGIXML_NO_STL
  4197. PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const wchar_t* str)
  4198. {
  4199. assert(str);
  4200. return impl::as_utf8_impl(str, wcslen(str));
  4201. }
  4202. PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t>& str)
  4203. {
  4204. return impl::as_utf8_impl(str.c_str(), str.size());
  4205. }
  4206. PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const char* str)
  4207. {
  4208. assert(str);
  4209. return impl::as_wide_impl(str, strlen(str));
  4210. }
  4211. PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const std::string& str)
  4212. {
  4213. return impl::as_wide_impl(str.c_str(), str.size());
  4214. }
  4215. #endif
  4216. PUGI__FN void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate)
  4217. {
  4218. impl::xml_memory::allocate = allocate;
  4219. impl::xml_memory::deallocate = deallocate;
  4220. }
  4221. PUGI__FN allocation_function PUGIXML_FUNCTION get_memory_allocation_function()
  4222. {
  4223. return impl::xml_memory::allocate;
  4224. }
  4225. PUGI__FN deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function()
  4226. {
  4227. return impl::xml_memory::deallocate;
  4228. }
  4229. }
  4230. #if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
  4231. namespace std
  4232. {
  4233. // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
  4234. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_node_iterator&)
  4235. {
  4236. return std::bidirectional_iterator_tag();
  4237. }
  4238. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_attribute_iterator&)
  4239. {
  4240. return std::bidirectional_iterator_tag();
  4241. }
  4242. PUGI__FN std::forward_iterator_tag _Iter_cat(const pugi::xml_named_node_iterator&)
  4243. {
  4244. return std::forward_iterator_tag();
  4245. }
  4246. }
  4247. #endif
  4248. #if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
  4249. namespace std
  4250. {
  4251. // Workarounds for (non-standard) iterator category detection
  4252. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_node_iterator&)
  4253. {
  4254. return std::bidirectional_iterator_tag();
  4255. }
  4256. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_attribute_iterator&)
  4257. {
  4258. return std::bidirectional_iterator_tag();
  4259. }
  4260. PUGI__FN std::forward_iterator_tag __iterator_category(const pugi::xml_named_node_iterator&)
  4261. {
  4262. return std::forward_iterator_tag();
  4263. }
  4264. }
  4265. #endif
  4266. #ifndef PUGIXML_NO_XPATH
  4267. // STL replacements
  4268. PUGI__NS_BEGIN
  4269. struct equal_to
  4270. {
  4271. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4272. {
  4273. return lhs == rhs;
  4274. }
  4275. };
  4276. struct not_equal_to
  4277. {
  4278. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4279. {
  4280. return lhs != rhs;
  4281. }
  4282. };
  4283. struct less
  4284. {
  4285. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4286. {
  4287. return lhs < rhs;
  4288. }
  4289. };
  4290. struct less_equal
  4291. {
  4292. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  4293. {
  4294. return lhs <= rhs;
  4295. }
  4296. };
  4297. template <typename T> void swap(T& lhs, T& rhs)
  4298. {
  4299. T temp = lhs;
  4300. lhs = rhs;
  4301. rhs = temp;
  4302. }
  4303. template <typename I, typename Pred> I min_element(I begin, I end, const Pred& pred)
  4304. {
  4305. I result = begin;
  4306. for (I it = begin + 1; it != end; ++it)
  4307. if (pred(*it, *result))
  4308. result = it;
  4309. return result;
  4310. }
  4311. template <typename I> void reverse(I begin, I end)
  4312. {
  4313. while (begin + 1 < end) swap(*begin++, *--end);
  4314. }
  4315. template <typename I> I unique(I begin, I end)
  4316. {
  4317. // fast skip head
  4318. while (begin + 1 < end && *begin != *(begin + 1)) begin++;
  4319. if (begin == end) return begin;
  4320. // last written element
  4321. I write = begin++;
  4322. // merge unique elements
  4323. while (begin != end)
  4324. {
  4325. if (*begin != *write)
  4326. *++write = *begin++;
  4327. else
  4328. begin++;
  4329. }
  4330. // past-the-end (write points to live element)
  4331. return write + 1;
  4332. }
  4333. template <typename I> void copy_backwards(I begin, I end, I target)
  4334. {
  4335. while (begin != end) *--target = *--end;
  4336. }
  4337. template <typename I, typename Pred, typename T> void insertion_sort(I begin, I end, const Pred& pred, T*)
  4338. {
  4339. assert(begin != end);
  4340. for (I it = begin + 1; it != end; ++it)
  4341. {
  4342. T val = *it;
  4343. if (pred(val, *begin))
  4344. {
  4345. // move to front
  4346. copy_backwards(begin, it, it + 1);
  4347. *begin = val;
  4348. }
  4349. else
  4350. {
  4351. I hole = it;
  4352. // move hole backwards
  4353. while (pred(val, *(hole - 1)))
  4354. {
  4355. *hole = *(hole - 1);
  4356. hole--;
  4357. }
  4358. // fill hole with element
  4359. *hole = val;
  4360. }
  4361. }
  4362. }
  4363. // std variant for elements with ==
  4364. template <typename I, typename Pred> void partition(I begin, I middle, I end, const Pred& pred, I* out_eqbeg, I* out_eqend)
  4365. {
  4366. I eqbeg = middle, eqend = middle + 1;
  4367. // expand equal range
  4368. while (eqbeg != begin && *(eqbeg - 1) == *eqbeg) --eqbeg;
  4369. while (eqend != end && *eqend == *eqbeg) ++eqend;
  4370. // process outer elements
  4371. I ltend = eqbeg, gtbeg = eqend;
  4372. for (;;)
  4373. {
  4374. // find the element from the right side that belongs to the left one
  4375. for (; gtbeg != end; ++gtbeg)
  4376. if (!pred(*eqbeg, *gtbeg))
  4377. {
  4378. if (*gtbeg == *eqbeg) swap(*gtbeg, *eqend++);
  4379. else break;
  4380. }
  4381. // find the element from the left side that belongs to the right one
  4382. for (; ltend != begin; --ltend)
  4383. if (!pred(*(ltend - 1), *eqbeg))
  4384. {
  4385. if (*eqbeg == *(ltend - 1)) swap(*(ltend - 1), *--eqbeg);
  4386. else break;
  4387. }
  4388. // scanned all elements
  4389. if (gtbeg == end && ltend == begin)
  4390. {
  4391. *out_eqbeg = eqbeg;
  4392. *out_eqend = eqend;
  4393. return;
  4394. }
  4395. // make room for elements by moving equal area
  4396. if (gtbeg == end)
  4397. {
  4398. if (--ltend != --eqbeg) swap(*ltend, *eqbeg);
  4399. swap(*eqbeg, *--eqend);
  4400. }
  4401. else if (ltend == begin)
  4402. {
  4403. if (eqend != gtbeg) swap(*eqbeg, *eqend);
  4404. ++eqend;
  4405. swap(*gtbeg++, *eqbeg++);
  4406. }
  4407. else swap(*gtbeg++, *--ltend);
  4408. }
  4409. }
  4410. template <typename I, typename Pred> void median3(I first, I middle, I last, const Pred& pred)
  4411. {
  4412. if (pred(*middle, *first)) swap(*middle, *first);
  4413. if (pred(*last, *middle)) swap(*last, *middle);
  4414. if (pred(*middle, *first)) swap(*middle, *first);
  4415. }
  4416. template <typename I, typename Pred> void median(I first, I middle, I last, const Pred& pred)
  4417. {
  4418. if (last - first <= 40)
  4419. {
  4420. // median of three for small chunks
  4421. median3(first, middle, last, pred);
  4422. }
  4423. else
  4424. {
  4425. // median of nine
  4426. size_t step = (last - first + 1) / 8;
  4427. median3(first, first + step, first + 2 * step, pred);
  4428. median3(middle - step, middle, middle + step, pred);
  4429. median3(last - 2 * step, last - step, last, pred);
  4430. median3(first + step, middle, last - step, pred);
  4431. }
  4432. }
  4433. template <typename I, typename Pred> void sort(I begin, I end, const Pred& pred)
  4434. {
  4435. // sort large chunks
  4436. while (end - begin > 32)
  4437. {
  4438. // find median element
  4439. I middle = begin + (end - begin) / 2;
  4440. median(begin, middle, end - 1, pred);
  4441. // partition in three chunks (< = >)
  4442. I eqbeg, eqend;
  4443. partition(begin, middle, end, pred, &eqbeg, &eqend);
  4444. // loop on larger half
  4445. if (eqbeg - begin > end - eqend)
  4446. {
  4447. sort(eqend, end, pred);
  4448. end = eqbeg;
  4449. }
  4450. else
  4451. {
  4452. sort(begin, eqbeg, pred);
  4453. begin = eqend;
  4454. }
  4455. }
  4456. // insertion sort small chunk
  4457. if (begin != end) insertion_sort(begin, end, pred, &*begin);
  4458. }
  4459. PUGI__NS_END
  4460. // Allocator used for AST and evaluation stacks
  4461. PUGI__NS_BEGIN
  4462. struct xpath_memory_block
  4463. {
  4464. xpath_memory_block* next;
  4465. char data[
  4466. #ifdef PUGIXML_MEMORY_XPATH_PAGE_SIZE
  4467. PUGIXML_MEMORY_XPATH_PAGE_SIZE
  4468. #else
  4469. 4096
  4470. #endif
  4471. ];
  4472. };
  4473. class xpath_allocator
  4474. {
  4475. xpath_memory_block* _root;
  4476. size_t _root_size;
  4477. public:
  4478. #ifdef PUGIXML_NO_EXCEPTIONS
  4479. jmp_buf* error_handler;
  4480. #endif
  4481. xpath_allocator(xpath_memory_block* root, size_t root_size = 0): _root(root), _root_size(root_size)
  4482. {
  4483. #ifdef PUGIXML_NO_EXCEPTIONS
  4484. error_handler = 0;
  4485. #endif
  4486. }
  4487. void* allocate_nothrow(size_t size)
  4488. {
  4489. const size_t block_capacity = sizeof(_root->data);
  4490. // align size so that we're able to store pointers in subsequent blocks
  4491. size = (size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);
  4492. if (_root_size + size <= block_capacity)
  4493. {
  4494. void* buf = _root->data + _root_size;
  4495. _root_size += size;
  4496. return buf;
  4497. }
  4498. else
  4499. {
  4500. size_t block_data_size = (size > block_capacity) ? size : block_capacity;
  4501. size_t block_size = block_data_size + offsetof(xpath_memory_block, data);
  4502. xpath_memory_block* block = static_cast<xpath_memory_block*>(xml_memory::allocate(block_size));
  4503. if (!block) return 0;
  4504. block->next = _root;
  4505. _root = block;
  4506. _root_size = size;
  4507. return block->data;
  4508. }
  4509. }
  4510. void* allocate(size_t size)
  4511. {
  4512. void* result = allocate_nothrow(size);
  4513. if (!result)
  4514. {
  4515. #ifdef PUGIXML_NO_EXCEPTIONS
  4516. assert(error_handler);
  4517. longjmp(*error_handler, 1);
  4518. #else
  4519. throw std::bad_alloc();
  4520. #endif
  4521. }
  4522. return result;
  4523. }
  4524. void* reallocate(void* ptr, size_t old_size, size_t new_size)
  4525. {
  4526. // align size so that we're able to store pointers in subsequent blocks
  4527. old_size = (old_size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);
  4528. new_size = (new_size + sizeof(void*) - 1) & ~(sizeof(void*) - 1);
  4529. // we can only reallocate the last object
  4530. assert(ptr == 0 || static_cast<char*>(ptr) + old_size == _root->data + _root_size);
  4531. // adjust root size so that we have not allocated the object at all
  4532. bool only_object = (_root_size == old_size);
  4533. if (ptr) _root_size -= old_size;
  4534. // allocate a new version (this will obviously reuse the memory if possible)
  4535. void* result = allocate(new_size);
  4536. assert(result);
  4537. // we have a new block
  4538. if (result != ptr && ptr)
  4539. {
  4540. // copy old data
  4541. assert(new_size > old_size);
  4542. memcpy(result, ptr, old_size);
  4543. // free the previous page if it had no other objects
  4544. if (only_object)
  4545. {
  4546. assert(_root->data == result);
  4547. assert(_root->next);
  4548. xpath_memory_block* next = _root->next->next;
  4549. if (next)
  4550. {
  4551. // deallocate the whole page, unless it was the first one
  4552. xml_memory::deallocate(_root->next);
  4553. _root->next = next;
  4554. }
  4555. }
  4556. }
  4557. return result;
  4558. }
  4559. void revert(const xpath_allocator& state)
  4560. {
  4561. // free all new pages
  4562. xpath_memory_block* cur = _root;
  4563. while (cur != state._root)
  4564. {
  4565. xpath_memory_block* next = cur->next;
  4566. xml_memory::deallocate(cur);
  4567. cur = next;
  4568. }
  4569. // restore state
  4570. _root = state._root;
  4571. _root_size = state._root_size;
  4572. }
  4573. void release()
  4574. {
  4575. xpath_memory_block* cur = _root;
  4576. assert(cur);
  4577. while (cur->next)
  4578. {
  4579. xpath_memory_block* next = cur->next;
  4580. xml_memory::deallocate(cur);
  4581. cur = next;
  4582. }
  4583. }
  4584. };
  4585. struct xpath_allocator_capture
  4586. {
  4587. xpath_allocator_capture(xpath_allocator* alloc): _target(alloc), _state(*alloc)
  4588. {
  4589. }
  4590. ~xpath_allocator_capture()
  4591. {
  4592. _target->revert(_state);
  4593. }
  4594. xpath_allocator* _target;
  4595. xpath_allocator _state;
  4596. };
  4597. struct xpath_stack
  4598. {
  4599. xpath_allocator* result;
  4600. xpath_allocator* temp;
  4601. };
  4602. struct xpath_stack_data
  4603. {
  4604. xpath_memory_block blocks[2];
  4605. xpath_allocator result;
  4606. xpath_allocator temp;
  4607. xpath_stack stack;
  4608. #ifdef PUGIXML_NO_EXCEPTIONS
  4609. jmp_buf error_handler;
  4610. #endif
  4611. xpath_stack_data(): result(blocks + 0), temp(blocks + 1)
  4612. {
  4613. blocks[0].next = blocks[1].next = 0;
  4614. stack.result = &result;
  4615. stack.temp = &temp;
  4616. #ifdef PUGIXML_NO_EXCEPTIONS
  4617. result.error_handler = temp.error_handler = &error_handler;
  4618. #endif
  4619. }
  4620. ~xpath_stack_data()
  4621. {
  4622. result.release();
  4623. temp.release();
  4624. }
  4625. };
  4626. PUGI__NS_END
  4627. // String class
  4628. PUGI__NS_BEGIN
  4629. class xpath_string
  4630. {
  4631. const char_t* _buffer;
  4632. bool _uses_heap;
  4633. static char_t* duplicate_string(const char_t* string, size_t length, xpath_allocator* alloc)
  4634. {
  4635. char_t* result = static_cast<char_t*>(alloc->allocate((length + 1) * sizeof(char_t)));
  4636. assert(result);
  4637. memcpy(result, string, length * sizeof(char_t));
  4638. result[length] = 0;
  4639. return result;
  4640. }
  4641. static char_t* duplicate_string(const char_t* string, xpath_allocator* alloc)
  4642. {
  4643. return duplicate_string(string, strlength(string), alloc);
  4644. }
  4645. public:
  4646. xpath_string(): _buffer(PUGIXML_TEXT("")), _uses_heap(false)
  4647. {
  4648. }
  4649. explicit xpath_string(const char_t* str, xpath_allocator* alloc)
  4650. {
  4651. bool empty_ = (*str == 0);
  4652. _buffer = empty_ ? PUGIXML_TEXT("") : duplicate_string(str, alloc);
  4653. _uses_heap = !empty_;
  4654. }
  4655. explicit xpath_string(const char_t* str, bool use_heap): _buffer(str), _uses_heap(use_heap)
  4656. {
  4657. }
  4658. xpath_string(const char_t* begin, const char_t* end, xpath_allocator* alloc)
  4659. {
  4660. assert(begin <= end);
  4661. bool empty_ = (begin == end);
  4662. _buffer = empty_ ? PUGIXML_TEXT("") : duplicate_string(begin, static_cast<size_t>(end - begin), alloc);
  4663. _uses_heap = !empty_;
  4664. }
  4665. void append(const xpath_string& o, xpath_allocator* alloc)
  4666. {
  4667. // skip empty sources
  4668. if (!*o._buffer) return;
  4669. // fast append for constant empty target and constant source
  4670. if (!*_buffer && !_uses_heap && !o._uses_heap)
  4671. {
  4672. _buffer = o._buffer;
  4673. }
  4674. else
  4675. {
  4676. // need to make heap copy
  4677. size_t target_length = strlength(_buffer);
  4678. size_t source_length = strlength(o._buffer);
  4679. size_t result_length = target_length + source_length;
  4680. // allocate new buffer
  4681. char_t* result = static_cast<char_t*>(alloc->reallocate(_uses_heap ? const_cast<char_t*>(_buffer) : 0, (target_length + 1) * sizeof(char_t), (result_length + 1) * sizeof(char_t)));
  4682. assert(result);
  4683. // append first string to the new buffer in case there was no reallocation
  4684. if (!_uses_heap) memcpy(result, _buffer, target_length * sizeof(char_t));
  4685. // append second string to the new buffer
  4686. memcpy(result + target_length, o._buffer, source_length * sizeof(char_t));
  4687. result[result_length] = 0;
  4688. // finalize
  4689. _buffer = result;
  4690. _uses_heap = true;
  4691. }
  4692. }
  4693. const char_t* c_str() const
  4694. {
  4695. return _buffer;
  4696. }
  4697. size_t length() const
  4698. {
  4699. return strlength(_buffer);
  4700. }
  4701. char_t* data(xpath_allocator* alloc)
  4702. {
  4703. // make private heap copy
  4704. if (!_uses_heap)
  4705. {
  4706. _buffer = duplicate_string(_buffer, alloc);
  4707. _uses_heap = true;
  4708. }
  4709. return const_cast<char_t*>(_buffer);
  4710. }
  4711. bool empty() const
  4712. {
  4713. return *_buffer == 0;
  4714. }
  4715. bool operator==(const xpath_string& o) const
  4716. {
  4717. return strequal(_buffer, o._buffer);
  4718. }
  4719. bool operator!=(const xpath_string& o) const
  4720. {
  4721. return !strequal(_buffer, o._buffer);
  4722. }
  4723. bool uses_heap() const
  4724. {
  4725. return _uses_heap;
  4726. }
  4727. };
  4728. PUGI__FN xpath_string xpath_string_const(const char_t* str)
  4729. {
  4730. return xpath_string(str, false);
  4731. }
  4732. PUGI__NS_END
  4733. PUGI__NS_BEGIN
  4734. PUGI__FN bool starts_with(const char_t* string, const char_t* pattern)
  4735. {
  4736. while (*pattern && *string == *pattern)
  4737. {
  4738. string++;
  4739. pattern++;
  4740. }
  4741. return *pattern == 0;
  4742. }
  4743. PUGI__FN const char_t* find_char(const char_t* s, char_t c)
  4744. {
  4745. #ifdef PUGIXML_WCHAR_MODE
  4746. return wcschr(s, c);
  4747. #else
  4748. return strchr(s, c);
  4749. #endif
  4750. }
  4751. PUGI__FN const char_t* find_substring(const char_t* s, const char_t* p)
  4752. {
  4753. #ifdef PUGIXML_WCHAR_MODE
  4754. // MSVC6 wcsstr bug workaround (if s is empty it always returns 0)
  4755. return (*p == 0) ? s : wcsstr(s, p);
  4756. #else
  4757. return strstr(s, p);
  4758. #endif
  4759. }
  4760. // Converts symbol to lower case, if it is an ASCII one
  4761. PUGI__FN char_t tolower_ascii(char_t ch)
  4762. {
  4763. return static_cast<unsigned int>(ch - 'A') < 26 ? static_cast<char_t>(ch | ' ') : ch;
  4764. }
  4765. PUGI__FN xpath_string string_value(const xpath_node& na, xpath_allocator* alloc)
  4766. {
  4767. if (na.attribute())
  4768. return xpath_string_const(na.attribute().value());
  4769. else
  4770. {
  4771. const xml_node& n = na.node();
  4772. switch (n.type())
  4773. {
  4774. case node_pcdata:
  4775. case node_cdata:
  4776. case node_comment:
  4777. case node_pi:
  4778. return xpath_string_const(n.value());
  4779. case node_document:
  4780. case node_element:
  4781. {
  4782. xpath_string result;
  4783. xml_node cur = n.first_child();
  4784. while (cur && cur != n)
  4785. {
  4786. if (cur.type() == node_pcdata || cur.type() == node_cdata)
  4787. result.append(xpath_string_const(cur.value()), alloc);
  4788. if (cur.first_child())
  4789. cur = cur.first_child();
  4790. else if (cur.next_sibling())
  4791. cur = cur.next_sibling();
  4792. else
  4793. {
  4794. while (!cur.next_sibling() && cur != n)
  4795. cur = cur.parent();
  4796. if (cur != n) cur = cur.next_sibling();
  4797. }
  4798. }
  4799. return result;
  4800. }
  4801. default:
  4802. return xpath_string();
  4803. }
  4804. }
  4805. }
  4806. PUGI__FN unsigned int node_height(xml_node n)
  4807. {
  4808. unsigned int result = 0;
  4809. while (n)
  4810. {
  4811. ++result;
  4812. n = n.parent();
  4813. }
  4814. return result;
  4815. }
  4816. PUGI__FN bool node_is_before(xml_node ln, unsigned int lh, xml_node rn, unsigned int rh)
  4817. {
  4818. // normalize heights
  4819. for (unsigned int i = rh; i < lh; i++) ln = ln.parent();
  4820. for (unsigned int j = lh; j < rh; j++) rn = rn.parent();
  4821. // one node is the ancestor of the other
  4822. if (ln == rn) return lh < rh;
  4823. // find common ancestor
  4824. while (ln.parent() != rn.parent())
  4825. {
  4826. ln = ln.parent();
  4827. rn = rn.parent();
  4828. }
  4829. // there is no common ancestor (the shared parent is null), nodes are from different documents
  4830. if (!ln.parent()) return ln < rn;
  4831. // determine sibling order
  4832. for (; ln; ln = ln.next_sibling())
  4833. if (ln == rn)
  4834. return true;
  4835. return false;
  4836. }
  4837. PUGI__FN bool node_is_ancestor(xml_node parent, xml_node node)
  4838. {
  4839. while (node && node != parent) node = node.parent();
  4840. return parent && node == parent;
  4841. }
  4842. PUGI__FN const void* document_order(const xpath_node& xnode)
  4843. {
  4844. xml_node_struct* node = xnode.node().internal_object();
  4845. if (node)
  4846. {
  4847. if (node->name && (node->header & xml_memory_page_name_allocated_mask) == 0) return node->name;
  4848. if (node->value && (node->header & xml_memory_page_value_allocated_mask) == 0) return node->value;
  4849. return 0;
  4850. }
  4851. xml_attribute_struct* attr = xnode.attribute().internal_object();
  4852. if (attr)
  4853. {
  4854. if ((attr->header & xml_memory_page_name_allocated_mask) == 0) return attr->name;
  4855. if ((attr->header & xml_memory_page_value_allocated_mask) == 0) return attr->value;
  4856. return 0;
  4857. }
  4858. return 0;
  4859. }
  4860. struct document_order_comparator
  4861. {
  4862. bool operator()(const xpath_node& lhs, const xpath_node& rhs) const
  4863. {
  4864. // optimized document order based check
  4865. const void* lo = document_order(lhs);
  4866. const void* ro = document_order(rhs);
  4867. if (lo && ro) return lo < ro;
  4868. // slow comparison
  4869. xml_node ln = lhs.node(), rn = rhs.node();
  4870. // compare attributes
  4871. if (lhs.attribute() && rhs.attribute())
  4872. {
  4873. // shared parent
  4874. if (lhs.parent() == rhs.parent())
  4875. {
  4876. // determine sibling order
  4877. for (xml_attribute a = lhs.attribute(); a; a = a.next_attribute())
  4878. if (a == rhs.attribute())
  4879. return true;
  4880. return false;
  4881. }
  4882. // compare attribute parents
  4883. ln = lhs.parent();
  4884. rn = rhs.parent();
  4885. }
  4886. else if (lhs.attribute())
  4887. {
  4888. // attributes go after the parent element
  4889. if (lhs.parent() == rhs.node()) return false;
  4890. ln = lhs.parent();
  4891. }
  4892. else if (rhs.attribute())
  4893. {
  4894. // attributes go after the parent element
  4895. if (rhs.parent() == lhs.node()) return true;
  4896. rn = rhs.parent();
  4897. }
  4898. if (ln == rn) return false;
  4899. unsigned int lh = node_height(ln);
  4900. unsigned int rh = node_height(rn);
  4901. return node_is_before(ln, lh, rn, rh);
  4902. }
  4903. };
  4904. struct duplicate_comparator
  4905. {
  4906. bool operator()(const xpath_node& lhs, const xpath_node& rhs) const
  4907. {
  4908. if (lhs.attribute()) return rhs.attribute() ? lhs.attribute() < rhs.attribute() : true;
  4909. else return rhs.attribute() ? false : lhs.node() < rhs.node();
  4910. }
  4911. };
  4912. PUGI__FN double gen_nan()
  4913. {
  4914. #if defined(__STDC_IEC_559__) || ((FLT_RADIX - 0 == 2) && (FLT_MAX_EXP - 0 == 128) && (FLT_MANT_DIG - 0 == 24))
  4915. union { float f; uint32_t i; } u[sizeof(float) == sizeof(uint32_t) ? 1 : -1];
  4916. u[0].i = 0x7fc00000;
  4917. return u[0].f;
  4918. #else
  4919. // fallback
  4920. const volatile double zero = 0.0;
  4921. return zero / zero;
  4922. #endif
  4923. }
  4924. PUGI__FN bool is_nan(double value)
  4925. {
  4926. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
  4927. return !!_isnan(value);
  4928. #elif defined(fpclassify) && defined(FP_NAN)
  4929. return fpclassify(value) == FP_NAN;
  4930. #else
  4931. // fallback
  4932. const volatile double v = value;
  4933. return v != v;
  4934. #endif
  4935. }
  4936. PUGI__FN const char_t* convert_number_to_string_special(double value)
  4937. {
  4938. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
  4939. if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0;
  4940. if (_isnan(value)) return PUGIXML_TEXT("NaN");
  4941. return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  4942. #elif defined(fpclassify) && defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO)
  4943. switch (fpclassify(value))
  4944. {
  4945. case FP_NAN:
  4946. return PUGIXML_TEXT("NaN");
  4947. case FP_INFINITE:
  4948. return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  4949. case FP_ZERO:
  4950. return PUGIXML_TEXT("0");
  4951. default:
  4952. return 0;
  4953. }
  4954. #else
  4955. // fallback
  4956. const volatile double v = value;
  4957. if (v == 0) return PUGIXML_TEXT("0");
  4958. if (v != v) return PUGIXML_TEXT("NaN");
  4959. if (v * 2 == v) return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  4960. return 0;
  4961. #endif
  4962. }
  4963. PUGI__FN bool convert_number_to_boolean(double value)
  4964. {
  4965. return (value != 0 && !is_nan(value));
  4966. }
  4967. PUGI__FN void truncate_zeros(char* begin, char* end)
  4968. {
  4969. while (begin != end && end[-1] == '0') end--;
  4970. *end = 0;
  4971. }
  4972. // gets mantissa digits in the form of 0.xxxxx with 0. implied and the exponent
  4973. #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
  4974. PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent)
  4975. {
  4976. // get base values
  4977. int sign, exponent;
  4978. _ecvt_s(buffer, buffer_size, value, DBL_DIG + 1, &exponent, &sign);
  4979. // truncate redundant zeros
  4980. truncate_zeros(buffer, buffer + strlen(buffer));
  4981. // fill results
  4982. *out_mantissa = buffer;
  4983. *out_exponent = exponent;
  4984. }
  4985. #else
  4986. PUGI__FN void convert_number_to_mantissa_exponent(double value, char* buffer, size_t buffer_size, char** out_mantissa, int* out_exponent)
  4987. {
  4988. // get a scientific notation value with IEEE DBL_DIG decimals
  4989. sprintf(buffer, "%.*e", DBL_DIG, value);
  4990. assert(strlen(buffer) < buffer_size);
  4991. (void)!buffer_size;
  4992. // get the exponent (possibly negative)
  4993. char* exponent_string = strchr(buffer, 'e');
  4994. assert(exponent_string);
  4995. int exponent = atoi(exponent_string + 1);
  4996. // extract mantissa string: skip sign
  4997. char* mantissa = buffer[0] == '-' ? buffer + 1 : buffer;
  4998. assert(mantissa[0] != '0' && mantissa[1] == '.');
  4999. // divide mantissa by 10 to eliminate integer part
  5000. mantissa[1] = mantissa[0];
  5001. mantissa++;
  5002. exponent++;
  5003. // remove extra mantissa digits and zero-terminate mantissa
  5004. truncate_zeros(mantissa, exponent_string);
  5005. // fill results
  5006. *out_mantissa = mantissa;
  5007. *out_exponent = exponent;
  5008. }
  5009. #endif
  5010. PUGI__FN xpath_string convert_number_to_string(double value, xpath_allocator* alloc)
  5011. {
  5012. // try special number conversion
  5013. const char_t* special = convert_number_to_string_special(value);
  5014. if (special) return xpath_string_const(special);
  5015. // get mantissa + exponent form
  5016. char mantissa_buffer[64];
  5017. char* mantissa;
  5018. int exponent;
  5019. convert_number_to_mantissa_exponent(value, mantissa_buffer, sizeof(mantissa_buffer), &mantissa, &exponent);
  5020. // make the number!
  5021. char_t result[512];
  5022. char_t* s = result;
  5023. // sign
  5024. if (value < 0) *s++ = '-';
  5025. // integer part
  5026. if (exponent <= 0)
  5027. {
  5028. *s++ = '0';
  5029. }
  5030. else
  5031. {
  5032. while (exponent > 0)
  5033. {
  5034. assert(*mantissa == 0 || static_cast<unsigned int>(*mantissa - '0') <= 9);
  5035. *s++ = *mantissa ? *mantissa++ : '0';
  5036. exponent--;
  5037. }
  5038. }
  5039. // fractional part
  5040. if (*mantissa)
  5041. {
  5042. // decimal point
  5043. *s++ = '.';
  5044. // extra zeroes from negative exponent
  5045. while (exponent < 0)
  5046. {
  5047. *s++ = '0';
  5048. exponent++;
  5049. }
  5050. // extra mantissa digits
  5051. while (*mantissa)
  5052. {
  5053. assert(static_cast<unsigned int>(*mantissa - '0') <= 9);
  5054. *s++ = *mantissa++;
  5055. }
  5056. }
  5057. // zero-terminate
  5058. assert(s < result + sizeof(result) / sizeof(result[0]));
  5059. *s = 0;
  5060. return xpath_string(result, alloc);
  5061. }
  5062. PUGI__FN bool check_string_to_number_format(const char_t* string)
  5063. {
  5064. // parse leading whitespace
  5065. while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
  5066. // parse sign
  5067. if (*string == '-') ++string;
  5068. if (!*string) return false;
  5069. // if there is no integer part, there should be a decimal part with at least one digit
  5070. if (!PUGI__IS_CHARTYPEX(string[0], ctx_digit) && (string[0] != '.' || !PUGI__IS_CHARTYPEX(string[1], ctx_digit))) return false;
  5071. // parse integer part
  5072. while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
  5073. // parse decimal part
  5074. if (*string == '.')
  5075. {
  5076. ++string;
  5077. while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
  5078. }
  5079. // parse trailing whitespace
  5080. while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
  5081. return *string == 0;
  5082. }
  5083. PUGI__FN double convert_string_to_number(const char_t* string)
  5084. {
  5085. // check string format
  5086. if (!check_string_to_number_format(string)) return gen_nan();
  5087. // parse string
  5088. #ifdef PUGIXML_WCHAR_MODE
  5089. return wcstod(string, 0);
  5090. #else
  5091. return atof(string);
  5092. #endif
  5093. }
  5094. PUGI__FN bool convert_string_to_number(const char_t* begin, const char_t* end, double* out_result)
  5095. {
  5096. char_t buffer[32];
  5097. size_t length = static_cast<size_t>(end - begin);
  5098. char_t* scratch = buffer;
  5099. if (length >= sizeof(buffer) / sizeof(buffer[0]))
  5100. {
  5101. // need to make dummy on-heap copy
  5102. scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  5103. if (!scratch) return false;
  5104. }
  5105. // copy string to zero-terminated buffer and perform conversion
  5106. memcpy(scratch, begin, length * sizeof(char_t));
  5107. scratch[length] = 0;
  5108. *out_result = convert_string_to_number(scratch);
  5109. // free dummy buffer
  5110. if (scratch != buffer) xml_memory::deallocate(scratch);
  5111. return true;
  5112. }
  5113. PUGI__FN double round_nearest(double value)
  5114. {
  5115. return floor(value + 0.5);
  5116. }
  5117. PUGI__FN double round_nearest_nzero(double value)
  5118. {
  5119. // same as round_nearest, but returns -0 for [-0.5, -0]
  5120. // ceil is used to differentiate between +0 and -0 (we return -0 for [-0.5, -0] and +0 for +0)
  5121. return (value >= -0.5 && value <= 0) ? ceil(value) : floor(value + 0.5);
  5122. }
  5123. PUGI__FN const char_t* qualified_name(const xpath_node& node)
  5124. {
  5125. return node.attribute() ? node.attribute().name() : node.node().name();
  5126. }
  5127. PUGI__FN const char_t* local_name(const xpath_node& node)
  5128. {
  5129. const char_t* name = qualified_name(node);
  5130. const char_t* p = find_char(name, ':');
  5131. return p ? p + 1 : name;
  5132. }
  5133. struct namespace_uri_predicate
  5134. {
  5135. const char_t* prefix;
  5136. size_t prefix_length;
  5137. namespace_uri_predicate(const char_t* name)
  5138. {
  5139. const char_t* pos = find_char(name, ':');
  5140. prefix = pos ? name : 0;
  5141. prefix_length = pos ? static_cast<size_t>(pos - name) : 0;
  5142. }
  5143. bool operator()(const xml_attribute& a) const
  5144. {
  5145. const char_t* name = a.name();
  5146. if (!starts_with(name, PUGIXML_TEXT("xmlns"))) return false;
  5147. return prefix ? name[5] == ':' && strequalrange(name + 6, prefix, prefix_length) : name[5] == 0;
  5148. }
  5149. };
  5150. PUGI__FN const char_t* namespace_uri(const xml_node& node)
  5151. {
  5152. namespace_uri_predicate pred = node.name();
  5153. xml_node p = node;
  5154. while (p)
  5155. {
  5156. xml_attribute a = p.find_attribute(pred);
  5157. if (a) return a.value();
  5158. p = p.parent();
  5159. }
  5160. return PUGIXML_TEXT("");
  5161. }
  5162. PUGI__FN const char_t* namespace_uri(const xml_attribute& attr, const xml_node& parent)
  5163. {
  5164. namespace_uri_predicate pred = attr.name();
  5165. // Default namespace does not apply to attributes
  5166. if (!pred.prefix) return PUGIXML_TEXT("");
  5167. xml_node p = parent;
  5168. while (p)
  5169. {
  5170. xml_attribute a = p.find_attribute(pred);
  5171. if (a) return a.value();
  5172. p = p.parent();
  5173. }
  5174. return PUGIXML_TEXT("");
  5175. }
  5176. PUGI__FN const char_t* namespace_uri(const xpath_node& node)
  5177. {
  5178. return node.attribute() ? namespace_uri(node.attribute(), node.parent()) : namespace_uri(node.node());
  5179. }
  5180. PUGI__FN void normalize_space(char_t* buffer)
  5181. {
  5182. char_t* write = buffer;
  5183. for (char_t* it = buffer; *it; )
  5184. {
  5185. char_t ch = *it++;
  5186. if (PUGI__IS_CHARTYPE(ch, ct_space))
  5187. {
  5188. // replace whitespace sequence with single space
  5189. while (PUGI__IS_CHARTYPE(*it, ct_space)) it++;
  5190. // avoid leading spaces
  5191. if (write != buffer) *write++ = ' ';
  5192. }
  5193. else *write++ = ch;
  5194. }
  5195. // remove trailing space
  5196. if (write != buffer && PUGI__IS_CHARTYPE(write[-1], ct_space)) write--;
  5197. // zero-terminate
  5198. *write = 0;
  5199. }
  5200. PUGI__FN void translate(char_t* buffer, const char_t* from, const char_t* to)
  5201. {
  5202. size_t to_length = strlength(to);
  5203. char_t* write = buffer;
  5204. while (*buffer)
  5205. {
  5206. PUGI__DMC_VOLATILE char_t ch = *buffer++;
  5207. const char_t* pos = find_char(from, ch);
  5208. if (!pos)
  5209. *write++ = ch; // do not process
  5210. else if (static_cast<size_t>(pos - from) < to_length)
  5211. *write++ = to[pos - from]; // replace
  5212. }
  5213. // zero-terminate
  5214. *write = 0;
  5215. }
  5216. struct xpath_variable_boolean: xpath_variable
  5217. {
  5218. xpath_variable_boolean(): value(false)
  5219. {
  5220. }
  5221. bool value;
  5222. char_t name[1];
  5223. };
  5224. struct xpath_variable_number: xpath_variable
  5225. {
  5226. xpath_variable_number(): value(0)
  5227. {
  5228. }
  5229. double value;
  5230. char_t name[1];
  5231. };
  5232. struct xpath_variable_string: xpath_variable
  5233. {
  5234. xpath_variable_string(): value(0)
  5235. {
  5236. }
  5237. ~xpath_variable_string()
  5238. {
  5239. if (value) xml_memory::deallocate(value);
  5240. }
  5241. char_t* value;
  5242. char_t name[1];
  5243. };
  5244. struct xpath_variable_node_set: xpath_variable
  5245. {
  5246. xpath_node_set value;
  5247. char_t name[1];
  5248. };
  5249. static const xpath_node_set dummy_node_set;
  5250. PUGI__FN unsigned int hash_string(const char_t* str)
  5251. {
  5252. // Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time)
  5253. unsigned int result = 0;
  5254. while (*str)
  5255. {
  5256. result += static_cast<unsigned int>(*str++);
  5257. result += result << 10;
  5258. result ^= result >> 6;
  5259. }
  5260. result += result << 3;
  5261. result ^= result >> 11;
  5262. result += result << 15;
  5263. return result;
  5264. }
  5265. template <typename T> PUGI__FN T* new_xpath_variable(const char_t* name)
  5266. {
  5267. size_t length = strlength(name);
  5268. if (length == 0) return 0; // empty variable names are invalid
  5269. // $$ we can't use offsetof(T, name) because T is non-POD, so we just allocate additional length characters
  5270. void* memory = xml_memory::allocate(sizeof(T) + length * sizeof(char_t));
  5271. if (!memory) return 0;
  5272. T* result = new (memory) T();
  5273. memcpy(result->name, name, (length + 1) * sizeof(char_t));
  5274. return result;
  5275. }
  5276. PUGI__FN xpath_variable* new_xpath_variable(xpath_value_type type, const char_t* name)
  5277. {
  5278. switch (type)
  5279. {
  5280. case xpath_type_node_set:
  5281. return new_xpath_variable<xpath_variable_node_set>(name);
  5282. case xpath_type_number:
  5283. return new_xpath_variable<xpath_variable_number>(name);
  5284. case xpath_type_string:
  5285. return new_xpath_variable<xpath_variable_string>(name);
  5286. case xpath_type_boolean:
  5287. return new_xpath_variable<xpath_variable_boolean>(name);
  5288. default:
  5289. return 0;
  5290. }
  5291. }
  5292. template <typename T> PUGI__FN void delete_xpath_variable(T* var)
  5293. {
  5294. var->~T();
  5295. xml_memory::deallocate(var);
  5296. }
  5297. PUGI__FN void delete_xpath_variable(xpath_value_type type, xpath_variable* var)
  5298. {
  5299. switch (type)
  5300. {
  5301. case xpath_type_node_set:
  5302. delete_xpath_variable(static_cast<xpath_variable_node_set*>(var));
  5303. break;
  5304. case xpath_type_number:
  5305. delete_xpath_variable(static_cast<xpath_variable_number*>(var));
  5306. break;
  5307. case xpath_type_string:
  5308. delete_xpath_variable(static_cast<xpath_variable_string*>(var));
  5309. break;
  5310. case xpath_type_boolean:
  5311. delete_xpath_variable(static_cast<xpath_variable_boolean*>(var));
  5312. break;
  5313. default:
  5314. assert(!"Invalid variable type");
  5315. }
  5316. }
  5317. PUGI__FN xpath_variable* get_variable(xpath_variable_set* set, const char_t* begin, const char_t* end)
  5318. {
  5319. char_t buffer[32];
  5320. size_t length = static_cast<size_t>(end - begin);
  5321. char_t* scratch = buffer;
  5322. if (length >= sizeof(buffer) / sizeof(buffer[0]))
  5323. {
  5324. // need to make dummy on-heap copy
  5325. scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  5326. if (!scratch) return 0;
  5327. }
  5328. // copy string to zero-terminated buffer and perform lookup
  5329. memcpy(scratch, begin, length * sizeof(char_t));
  5330. scratch[length] = 0;
  5331. xpath_variable* result = set->get(scratch);
  5332. // free dummy buffer
  5333. if (scratch != buffer) xml_memory::deallocate(scratch);
  5334. return result;
  5335. }
  5336. PUGI__NS_END
  5337. // Internal node set class
  5338. PUGI__NS_BEGIN
  5339. PUGI__FN xpath_node_set::type_t xpath_sort(xpath_node* begin, xpath_node* end, xpath_node_set::type_t type, bool rev)
  5340. {
  5341. xpath_node_set::type_t order = rev ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
  5342. if (type == xpath_node_set::type_unsorted)
  5343. {
  5344. sort(begin, end, document_order_comparator());
  5345. type = xpath_node_set::type_sorted;
  5346. }
  5347. if (type != order) reverse(begin, end);
  5348. return order;
  5349. }
  5350. PUGI__FN xpath_node xpath_first(const xpath_node* begin, const xpath_node* end, xpath_node_set::type_t type)
  5351. {
  5352. if (begin == end) return xpath_node();
  5353. switch (type)
  5354. {
  5355. case xpath_node_set::type_sorted:
  5356. return *begin;
  5357. case xpath_node_set::type_sorted_reverse:
  5358. return *(end - 1);
  5359. case xpath_node_set::type_unsorted:
  5360. return *min_element(begin, end, document_order_comparator());
  5361. default:
  5362. assert(!"Invalid node set type");
  5363. return xpath_node();
  5364. }
  5365. }
  5366. class xpath_node_set_raw
  5367. {
  5368. xpath_node_set::type_t _type;
  5369. xpath_node* _begin;
  5370. xpath_node* _end;
  5371. xpath_node* _eos;
  5372. public:
  5373. xpath_node_set_raw(): _type(xpath_node_set::type_unsorted), _begin(0), _end(0), _eos(0)
  5374. {
  5375. }
  5376. xpath_node* begin() const
  5377. {
  5378. return _begin;
  5379. }
  5380. xpath_node* end() const
  5381. {
  5382. return _end;
  5383. }
  5384. bool empty() const
  5385. {
  5386. return _begin == _end;
  5387. }
  5388. size_t size() const
  5389. {
  5390. return static_cast<size_t>(_end - _begin);
  5391. }
  5392. xpath_node first() const
  5393. {
  5394. return xpath_first(_begin, _end, _type);
  5395. }
  5396. void push_back(const xpath_node& node, xpath_allocator* alloc)
  5397. {
  5398. if (_end == _eos)
  5399. {
  5400. size_t capacity = static_cast<size_t>(_eos - _begin);
  5401. // get new capacity (1.5x rule)
  5402. size_t new_capacity = capacity + capacity / 2 + 1;
  5403. // reallocate the old array or allocate a new one
  5404. xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), new_capacity * sizeof(xpath_node)));
  5405. assert(data);
  5406. // finalize
  5407. _begin = data;
  5408. _end = data + capacity;
  5409. _eos = data + new_capacity;
  5410. }
  5411. *_end++ = node;
  5412. }
  5413. void append(const xpath_node* begin_, const xpath_node* end_, xpath_allocator* alloc)
  5414. {
  5415. size_t size_ = static_cast<size_t>(_end - _begin);
  5416. size_t capacity = static_cast<size_t>(_eos - _begin);
  5417. size_t count = static_cast<size_t>(end_ - begin_);
  5418. if (size_ + count > capacity)
  5419. {
  5420. // reallocate the old array or allocate a new one
  5421. xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), (size_ + count) * sizeof(xpath_node)));
  5422. assert(data);
  5423. // finalize
  5424. _begin = data;
  5425. _end = data + size_;
  5426. _eos = data + size_ + count;
  5427. }
  5428. memcpy(_end, begin_, count * sizeof(xpath_node));
  5429. _end += count;
  5430. }
  5431. void sort_do()
  5432. {
  5433. _type = xpath_sort(_begin, _end, _type, false);
  5434. }
  5435. void truncate(xpath_node* pos)
  5436. {
  5437. assert(_begin <= pos && pos <= _end);
  5438. _end = pos;
  5439. }
  5440. void remove_duplicates()
  5441. {
  5442. if (_type == xpath_node_set::type_unsorted)
  5443. sort(_begin, _end, duplicate_comparator());
  5444. _end = unique(_begin, _end);
  5445. }
  5446. xpath_node_set::type_t type() const
  5447. {
  5448. return _type;
  5449. }
  5450. void set_type(xpath_node_set::type_t value)
  5451. {
  5452. _type = value;
  5453. }
  5454. };
  5455. PUGI__NS_END
  5456. PUGI__NS_BEGIN
  5457. struct xpath_context
  5458. {
  5459. xpath_node n;
  5460. size_t position, size;
  5461. xpath_context(const xpath_node& n_, size_t position_, size_t size_): n(n_), position(position_), size(size_)
  5462. {
  5463. }
  5464. };
  5465. enum lexeme_t
  5466. {
  5467. lex_none = 0,
  5468. lex_equal,
  5469. lex_not_equal,
  5470. lex_less,
  5471. lex_greater,
  5472. lex_less_or_equal,
  5473. lex_greater_or_equal,
  5474. lex_plus,
  5475. lex_minus,
  5476. lex_multiply,
  5477. lex_union,
  5478. lex_var_ref,
  5479. lex_open_brace,
  5480. lex_close_brace,
  5481. lex_quoted_string,
  5482. lex_number,
  5483. lex_slash,
  5484. lex_double_slash,
  5485. lex_open_square_brace,
  5486. lex_close_square_brace,
  5487. lex_string,
  5488. lex_comma,
  5489. lex_axis_attribute,
  5490. lex_dot,
  5491. lex_double_dot,
  5492. lex_double_colon,
  5493. lex_eof
  5494. };
  5495. struct xpath_lexer_string
  5496. {
  5497. const char_t* begin;
  5498. const char_t* end;
  5499. xpath_lexer_string(): begin(0), end(0)
  5500. {
  5501. }
  5502. bool operator==(const char_t* other) const
  5503. {
  5504. size_t length = static_cast<size_t>(end - begin);
  5505. return strequalrange(other, begin, length);
  5506. }
  5507. };
  5508. class xpath_lexer
  5509. {
  5510. const char_t* _cur;
  5511. const char_t* _cur_lexeme_pos;
  5512. xpath_lexer_string _cur_lexeme_contents;
  5513. lexeme_t _cur_lexeme;
  5514. public:
  5515. explicit xpath_lexer(const char_t* query): _cur(query)
  5516. {
  5517. next();
  5518. }
  5519. const char_t* state() const
  5520. {
  5521. return _cur;
  5522. }
  5523. void next()
  5524. {
  5525. const char_t* cur = _cur;
  5526. while (PUGI__IS_CHARTYPE(*cur, ct_space)) ++cur;
  5527. // save lexeme position for error reporting
  5528. _cur_lexeme_pos = cur;
  5529. switch (*cur)
  5530. {
  5531. case 0:
  5532. _cur_lexeme = lex_eof;
  5533. break;
  5534. case '>':
  5535. if (*(cur+1) == '=')
  5536. {
  5537. cur += 2;
  5538. _cur_lexeme = lex_greater_or_equal;
  5539. }
  5540. else
  5541. {
  5542. cur += 1;
  5543. _cur_lexeme = lex_greater;
  5544. }
  5545. break;
  5546. case '<':
  5547. if (*(cur+1) == '=')
  5548. {
  5549. cur += 2;
  5550. _cur_lexeme = lex_less_or_equal;
  5551. }
  5552. else
  5553. {
  5554. cur += 1;
  5555. _cur_lexeme = lex_less;
  5556. }
  5557. break;
  5558. case '!':
  5559. if (*(cur+1) == '=')
  5560. {
  5561. cur += 2;
  5562. _cur_lexeme = lex_not_equal;
  5563. }
  5564. else
  5565. {
  5566. _cur_lexeme = lex_none;
  5567. }
  5568. break;
  5569. case '=':
  5570. cur += 1;
  5571. _cur_lexeme = lex_equal;
  5572. break;
  5573. case '+':
  5574. cur += 1;
  5575. _cur_lexeme = lex_plus;
  5576. break;
  5577. case '-':
  5578. cur += 1;
  5579. _cur_lexeme = lex_minus;
  5580. break;
  5581. case '*':
  5582. cur += 1;
  5583. _cur_lexeme = lex_multiply;
  5584. break;
  5585. case '|':
  5586. cur += 1;
  5587. _cur_lexeme = lex_union;
  5588. break;
  5589. case '$':
  5590. cur += 1;
  5591. if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
  5592. {
  5593. _cur_lexeme_contents.begin = cur;
  5594. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  5595. if (cur[0] == ':' && PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // qname
  5596. {
  5597. cur++; // :
  5598. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  5599. }
  5600. _cur_lexeme_contents.end = cur;
  5601. _cur_lexeme = lex_var_ref;
  5602. }
  5603. else
  5604. {
  5605. _cur_lexeme = lex_none;
  5606. }
  5607. break;
  5608. case '(':
  5609. cur += 1;
  5610. _cur_lexeme = lex_open_brace;
  5611. break;
  5612. case ')':
  5613. cur += 1;
  5614. _cur_lexeme = lex_close_brace;
  5615. break;
  5616. case '[':
  5617. cur += 1;
  5618. _cur_lexeme = lex_open_square_brace;
  5619. break;
  5620. case ']':
  5621. cur += 1;
  5622. _cur_lexeme = lex_close_square_brace;
  5623. break;
  5624. case ',':
  5625. cur += 1;
  5626. _cur_lexeme = lex_comma;
  5627. break;
  5628. case '/':
  5629. if (*(cur+1) == '/')
  5630. {
  5631. cur += 2;
  5632. _cur_lexeme = lex_double_slash;
  5633. }
  5634. else
  5635. {
  5636. cur += 1;
  5637. _cur_lexeme = lex_slash;
  5638. }
  5639. break;
  5640. case '.':
  5641. if (*(cur+1) == '.')
  5642. {
  5643. cur += 2;
  5644. _cur_lexeme = lex_double_dot;
  5645. }
  5646. else if (PUGI__IS_CHARTYPEX(*(cur+1), ctx_digit))
  5647. {
  5648. _cur_lexeme_contents.begin = cur; // .
  5649. ++cur;
  5650. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  5651. _cur_lexeme_contents.end = cur;
  5652. _cur_lexeme = lex_number;
  5653. }
  5654. else
  5655. {
  5656. cur += 1;
  5657. _cur_lexeme = lex_dot;
  5658. }
  5659. break;
  5660. case '@':
  5661. cur += 1;
  5662. _cur_lexeme = lex_axis_attribute;
  5663. break;
  5664. case '"':
  5665. case '\'':
  5666. {
  5667. char_t terminator = *cur;
  5668. ++cur;
  5669. _cur_lexeme_contents.begin = cur;
  5670. while (*cur && *cur != terminator) cur++;
  5671. _cur_lexeme_contents.end = cur;
  5672. if (!*cur)
  5673. _cur_lexeme = lex_none;
  5674. else
  5675. {
  5676. cur += 1;
  5677. _cur_lexeme = lex_quoted_string;
  5678. }
  5679. break;
  5680. }
  5681. case ':':
  5682. if (*(cur+1) == ':')
  5683. {
  5684. cur += 2;
  5685. _cur_lexeme = lex_double_colon;
  5686. }
  5687. else
  5688. {
  5689. _cur_lexeme = lex_none;
  5690. }
  5691. break;
  5692. default:
  5693. if (PUGI__IS_CHARTYPEX(*cur, ctx_digit))
  5694. {
  5695. _cur_lexeme_contents.begin = cur;
  5696. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  5697. if (*cur == '.')
  5698. {
  5699. cur++;
  5700. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  5701. }
  5702. _cur_lexeme_contents.end = cur;
  5703. _cur_lexeme = lex_number;
  5704. }
  5705. else if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
  5706. {
  5707. _cur_lexeme_contents.begin = cur;
  5708. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  5709. if (cur[0] == ':')
  5710. {
  5711. if (cur[1] == '*') // namespace test ncname:*
  5712. {
  5713. cur += 2; // :*
  5714. }
  5715. else if (PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // namespace test qname
  5716. {
  5717. cur++; // :
  5718. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  5719. }
  5720. }
  5721. _cur_lexeme_contents.end = cur;
  5722. _cur_lexeme = lex_string;
  5723. }
  5724. else
  5725. {
  5726. _cur_lexeme = lex_none;
  5727. }
  5728. }
  5729. _cur = cur;
  5730. }
  5731. lexeme_t current() const
  5732. {
  5733. return _cur_lexeme;
  5734. }
  5735. const char_t* current_pos() const
  5736. {
  5737. return _cur_lexeme_pos;
  5738. }
  5739. const xpath_lexer_string& contents() const
  5740. {
  5741. assert(_cur_lexeme == lex_var_ref || _cur_lexeme == lex_number || _cur_lexeme == lex_string || _cur_lexeme == lex_quoted_string);
  5742. return _cur_lexeme_contents;
  5743. }
  5744. };
  5745. enum ast_type_t
  5746. {
  5747. ast_op_or, // left or right
  5748. ast_op_and, // left and right
  5749. ast_op_equal, // left = right
  5750. ast_op_not_equal, // left != right
  5751. ast_op_less, // left < right
  5752. ast_op_greater, // left > right
  5753. ast_op_less_or_equal, // left <= right
  5754. ast_op_greater_or_equal, // left >= right
  5755. ast_op_add, // left + right
  5756. ast_op_subtract, // left - right
  5757. ast_op_multiply, // left * right
  5758. ast_op_divide, // left / right
  5759. ast_op_mod, // left % right
  5760. ast_op_negate, // left - right
  5761. ast_op_union, // left | right
  5762. ast_predicate, // apply predicate to set; next points to next predicate
  5763. ast_filter, // select * from left where right
  5764. ast_filter_posinv, // select * from left where right; proximity position invariant
  5765. ast_string_constant, // string constant
  5766. ast_number_constant, // number constant
  5767. ast_variable, // variable
  5768. ast_func_last, // last()
  5769. ast_func_position, // position()
  5770. ast_func_count, // count(left)
  5771. ast_func_id, // id(left)
  5772. ast_func_local_name_0, // local-name()
  5773. ast_func_local_name_1, // local-name(left)
  5774. ast_func_namespace_uri_0, // namespace-uri()
  5775. ast_func_namespace_uri_1, // namespace-uri(left)
  5776. ast_func_name_0, // name()
  5777. ast_func_name_1, // name(left)
  5778. ast_func_string_0, // string()
  5779. ast_func_string_1, // string(left)
  5780. ast_func_concat, // concat(left, right, siblings)
  5781. ast_func_starts_with, // starts_with(left, right)
  5782. ast_func_contains, // contains(left, right)
  5783. ast_func_substring_before, // substring-before(left, right)
  5784. ast_func_substring_after, // substring-after(left, right)
  5785. ast_func_substring_2, // substring(left, right)
  5786. ast_func_substring_3, // substring(left, right, third)
  5787. ast_func_string_length_0, // string-length()
  5788. ast_func_string_length_1, // string-length(left)
  5789. ast_func_normalize_space_0, // normalize-space()
  5790. ast_func_normalize_space_1, // normalize-space(left)
  5791. ast_func_translate, // translate(left, right, third)
  5792. ast_func_boolean, // boolean(left)
  5793. ast_func_not, // not(left)
  5794. ast_func_true, // true()
  5795. ast_func_false, // false()
  5796. ast_func_lang, // lang(left)
  5797. ast_func_number_0, // number()
  5798. ast_func_number_1, // number(left)
  5799. ast_func_sum, // sum(left)
  5800. ast_func_floor, // floor(left)
  5801. ast_func_ceiling, // ceiling(left)
  5802. ast_func_round, // round(left)
  5803. ast_step, // process set left with step
  5804. ast_step_root // select root node
  5805. };
  5806. enum axis_t
  5807. {
  5808. axis_ancestor,
  5809. axis_ancestor_or_self,
  5810. axis_attribute,
  5811. axis_child,
  5812. axis_descendant,
  5813. axis_descendant_or_self,
  5814. axis_following,
  5815. axis_following_sibling,
  5816. axis_namespace,
  5817. axis_parent,
  5818. axis_preceding,
  5819. axis_preceding_sibling,
  5820. axis_self
  5821. };
  5822. enum nodetest_t
  5823. {
  5824. nodetest_none,
  5825. nodetest_name,
  5826. nodetest_type_node,
  5827. nodetest_type_comment,
  5828. nodetest_type_pi,
  5829. nodetest_type_text,
  5830. nodetest_pi,
  5831. nodetest_all,
  5832. nodetest_all_in_namespace
  5833. };
  5834. template <axis_t N> struct axis_to_type
  5835. {
  5836. static const axis_t axis;
  5837. };
  5838. template <axis_t N> const axis_t axis_to_type<N>::axis = N;
  5839. class xpath_ast_node
  5840. {
  5841. private:
  5842. // node type
  5843. char _type;
  5844. char _rettype;
  5845. // for ast_step / ast_predicate
  5846. char _axis;
  5847. char _test;
  5848. // tree node structure
  5849. xpath_ast_node* _left;
  5850. xpath_ast_node* _right;
  5851. xpath_ast_node* _next;
  5852. union
  5853. {
  5854. // value for ast_string_constant
  5855. const char_t* string;
  5856. // value for ast_number_constant
  5857. double number;
  5858. // variable for ast_variable
  5859. xpath_variable* variable;
  5860. // node test for ast_step (node name/namespace/node type/pi target)
  5861. const char_t* nodetest;
  5862. } _data;
  5863. xpath_ast_node(const xpath_ast_node&);
  5864. xpath_ast_node& operator=(const xpath_ast_node&);
  5865. template <class Comp> static bool compare_eq(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)
  5866. {
  5867. xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
  5868. if (lt != xpath_type_node_set && rt != xpath_type_node_set)
  5869. {
  5870. if (lt == xpath_type_boolean || rt == xpath_type_boolean)
  5871. return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
  5872. else if (lt == xpath_type_number || rt == xpath_type_number)
  5873. return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
  5874. else if (lt == xpath_type_string || rt == xpath_type_string)
  5875. {
  5876. xpath_allocator_capture cr(stack.result);
  5877. xpath_string ls = lhs->eval_string(c, stack);
  5878. xpath_string rs = rhs->eval_string(c, stack);
  5879. return comp(ls, rs);
  5880. }
  5881. }
  5882. else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
  5883. {
  5884. xpath_allocator_capture cr(stack.result);
  5885. xpath_node_set_raw ls = lhs->eval_node_set(c, stack);
  5886. xpath_node_set_raw rs = rhs->eval_node_set(c, stack);
  5887. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  5888. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  5889. {
  5890. xpath_allocator_capture cri(stack.result);
  5891. if (comp(string_value(*li, stack.result), string_value(*ri, stack.result)))
  5892. return true;
  5893. }
  5894. return false;
  5895. }
  5896. else
  5897. {
  5898. if (lt == xpath_type_node_set)
  5899. {
  5900. swap(lhs, rhs);
  5901. swap(lt, rt);
  5902. }
  5903. if (lt == xpath_type_boolean)
  5904. return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
  5905. else if (lt == xpath_type_number)
  5906. {
  5907. xpath_allocator_capture cr(stack.result);
  5908. double l = lhs->eval_number(c, stack);
  5909. xpath_node_set_raw rs = rhs->eval_node_set(c, stack);
  5910. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  5911. {
  5912. xpath_allocator_capture cri(stack.result);
  5913. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  5914. return true;
  5915. }
  5916. return false;
  5917. }
  5918. else if (lt == xpath_type_string)
  5919. {
  5920. xpath_allocator_capture cr(stack.result);
  5921. xpath_string l = lhs->eval_string(c, stack);
  5922. xpath_node_set_raw rs = rhs->eval_node_set(c, stack);
  5923. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  5924. {
  5925. xpath_allocator_capture cri(stack.result);
  5926. if (comp(l, string_value(*ri, stack.result)))
  5927. return true;
  5928. }
  5929. return false;
  5930. }
  5931. }
  5932. assert(!"Wrong types");
  5933. return false;
  5934. }
  5935. template <class Comp> static bool compare_rel(xpath_ast_node* lhs, xpath_ast_node* rhs, const xpath_context& c, const xpath_stack& stack, const Comp& comp)
  5936. {
  5937. xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
  5938. if (lt != xpath_type_node_set && rt != xpath_type_node_set)
  5939. return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
  5940. else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
  5941. {
  5942. xpath_allocator_capture cr(stack.result);
  5943. xpath_node_set_raw ls = lhs->eval_node_set(c, stack);
  5944. xpath_node_set_raw rs = rhs->eval_node_set(c, stack);
  5945. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  5946. {
  5947. xpath_allocator_capture cri(stack.result);
  5948. double l = convert_string_to_number(string_value(*li, stack.result).c_str());
  5949. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  5950. {
  5951. xpath_allocator_capture crii(stack.result);
  5952. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  5953. return true;
  5954. }
  5955. }
  5956. return false;
  5957. }
  5958. else if (lt != xpath_type_node_set && rt == xpath_type_node_set)
  5959. {
  5960. xpath_allocator_capture cr(stack.result);
  5961. double l = lhs->eval_number(c, stack);
  5962. xpath_node_set_raw rs = rhs->eval_node_set(c, stack);
  5963. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  5964. {
  5965. xpath_allocator_capture cri(stack.result);
  5966. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  5967. return true;
  5968. }
  5969. return false;
  5970. }
  5971. else if (lt == xpath_type_node_set && rt != xpath_type_node_set)
  5972. {
  5973. xpath_allocator_capture cr(stack.result);
  5974. xpath_node_set_raw ls = lhs->eval_node_set(c, stack);
  5975. double r = rhs->eval_number(c, stack);
  5976. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  5977. {
  5978. xpath_allocator_capture cri(stack.result);
  5979. if (comp(convert_string_to_number(string_value(*li, stack.result).c_str()), r))
  5980. return true;
  5981. }
  5982. return false;
  5983. }
  5984. else
  5985. {
  5986. assert(!"Wrong types");
  5987. return false;
  5988. }
  5989. }
  5990. void apply_predicate(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack)
  5991. {
  5992. assert(ns.size() >= first);
  5993. size_t i = 1;
  5994. size_t size = ns.size() - first;
  5995. xpath_node* last = ns.begin() + first;
  5996. // remove_if... or well, sort of
  5997. for (xpath_node* it = last; it != ns.end(); ++it, ++i)
  5998. {
  5999. xpath_context c(*it, i, size);
  6000. if (expr->rettype() == xpath_type_number)
  6001. {
  6002. if (expr->eval_number(c, stack) == i)
  6003. *last++ = *it;
  6004. }
  6005. else if (expr->eval_boolean(c, stack))
  6006. *last++ = *it;
  6007. }
  6008. ns.truncate(last);
  6009. }
  6010. void apply_predicates(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack)
  6011. {
  6012. if (ns.size() == first) return;
  6013. for (xpath_ast_node* pred = _right; pred; pred = pred->_next)
  6014. {
  6015. apply_predicate(ns, first, pred->_left, stack);
  6016. }
  6017. }
  6018. void step_push(xpath_node_set_raw& ns, const xml_attribute& a, const xml_node& parent, xpath_allocator* alloc)
  6019. {
  6020. if (!a) return;
  6021. const char_t* name = a.name();
  6022. // There are no attribute nodes corresponding to attributes that declare namespaces
  6023. // That is, "xmlns:..." or "xmlns"
  6024. if (starts_with(name, PUGIXML_TEXT("xmlns")) && (name[5] == 0 || name[5] == ':')) return;
  6025. switch (_test)
  6026. {
  6027. case nodetest_name:
  6028. if (strequal(name, _data.nodetest)) ns.push_back(xpath_node(a, parent), alloc);
  6029. break;
  6030. case nodetest_type_node:
  6031. case nodetest_all:
  6032. ns.push_back(xpath_node(a, parent), alloc);
  6033. break;
  6034. case nodetest_all_in_namespace:
  6035. if (starts_with(name, _data.nodetest))
  6036. ns.push_back(xpath_node(a, parent), alloc);
  6037. break;
  6038. default:
  6039. ;
  6040. }
  6041. }
  6042. void step_push(xpath_node_set_raw& ns, const xml_node& n, xpath_allocator* alloc)
  6043. {
  6044. if (!n) return;
  6045. switch (_test)
  6046. {
  6047. case nodetest_name:
  6048. if (n.type() == node_element && strequal(n.name(), _data.nodetest)) ns.push_back(n, alloc);
  6049. break;
  6050. case nodetest_type_node:
  6051. ns.push_back(n, alloc);
  6052. break;
  6053. case nodetest_type_comment:
  6054. if (n.type() == node_comment)
  6055. ns.push_back(n, alloc);
  6056. break;
  6057. case nodetest_type_text:
  6058. if (n.type() == node_pcdata || n.type() == node_cdata)
  6059. ns.push_back(n, alloc);
  6060. break;
  6061. case nodetest_type_pi:
  6062. if (n.type() == node_pi)
  6063. ns.push_back(n, alloc);
  6064. break;
  6065. case nodetest_pi:
  6066. if (n.type() == node_pi && strequal(n.name(), _data.nodetest))
  6067. ns.push_back(n, alloc);
  6068. break;
  6069. case nodetest_all:
  6070. if (n.type() == node_element)
  6071. ns.push_back(n, alloc);
  6072. break;
  6073. case nodetest_all_in_namespace:
  6074. if (n.type() == node_element && starts_with(n.name(), _data.nodetest))
  6075. ns.push_back(n, alloc);
  6076. break;
  6077. default:
  6078. assert(!"Unknown axis");
  6079. }
  6080. }
  6081. template <class T> void step_fill(xpath_node_set_raw& ns, const xml_node& n, xpath_allocator* alloc, T)
  6082. {
  6083. const axis_t axis = T::axis;
  6084. switch (axis)
  6085. {
  6086. case axis_attribute:
  6087. {
  6088. for (xml_attribute a = n.first_attribute(); a; a = a.next_attribute())
  6089. step_push(ns, a, n, alloc);
  6090. break;
  6091. }
  6092. case axis_child:
  6093. {
  6094. for (xml_node c = n.first_child(); c; c = c.next_sibling())
  6095. step_push(ns, c, alloc);
  6096. break;
  6097. }
  6098. case axis_descendant:
  6099. case axis_descendant_or_self:
  6100. {
  6101. if (axis == axis_descendant_or_self)
  6102. step_push(ns, n, alloc);
  6103. xml_node cur = n.first_child();
  6104. while (cur && cur != n)
  6105. {
  6106. step_push(ns, cur, alloc);
  6107. if (cur.first_child())
  6108. cur = cur.first_child();
  6109. else if (cur.next_sibling())
  6110. cur = cur.next_sibling();
  6111. else
  6112. {
  6113. while (!cur.next_sibling() && cur != n)
  6114. cur = cur.parent();
  6115. if (cur != n) cur = cur.next_sibling();
  6116. }
  6117. }
  6118. break;
  6119. }
  6120. case axis_following_sibling:
  6121. {
  6122. for (xml_node c = n.next_sibling(); c; c = c.next_sibling())
  6123. step_push(ns, c, alloc);
  6124. break;
  6125. }
  6126. case axis_preceding_sibling:
  6127. {
  6128. for (xml_node c = n.previous_sibling(); c; c = c.previous_sibling())
  6129. step_push(ns, c, alloc);
  6130. break;
  6131. }
  6132. case axis_following:
  6133. {
  6134. xml_node cur = n;
  6135. // exit from this node so that we don't include descendants
  6136. while (cur && !cur.next_sibling()) cur = cur.parent();
  6137. cur = cur.next_sibling();
  6138. for (;;)
  6139. {
  6140. step_push(ns, cur, alloc);
  6141. if (cur.first_child())
  6142. cur = cur.first_child();
  6143. else if (cur.next_sibling())
  6144. cur = cur.next_sibling();
  6145. else
  6146. {
  6147. while (cur && !cur.next_sibling()) cur = cur.parent();
  6148. cur = cur.next_sibling();
  6149. if (!cur) break;
  6150. }
  6151. }
  6152. break;
  6153. }
  6154. case axis_preceding:
  6155. {
  6156. xml_node cur = n;
  6157. while (cur && !cur.previous_sibling()) cur = cur.parent();
  6158. cur = cur.previous_sibling();
  6159. for (;;)
  6160. {
  6161. if (cur.last_child())
  6162. cur = cur.last_child();
  6163. else
  6164. {
  6165. // leaf node, can't be ancestor
  6166. step_push(ns, cur, alloc);
  6167. if (cur.previous_sibling())
  6168. cur = cur.previous_sibling();
  6169. else
  6170. {
  6171. do
  6172. {
  6173. cur = cur.parent();
  6174. if (!cur) break;
  6175. if (!node_is_ancestor(cur, n)) step_push(ns, cur, alloc);
  6176. }
  6177. while (!cur.previous_sibling());
  6178. cur = cur.previous_sibling();
  6179. if (!cur) break;
  6180. }
  6181. }
  6182. }
  6183. break;
  6184. }
  6185. case axis_ancestor:
  6186. case axis_ancestor_or_self:
  6187. {
  6188. if (axis == axis_ancestor_or_self)
  6189. step_push(ns, n, alloc);
  6190. xml_node cur = n.parent();
  6191. while (cur)
  6192. {
  6193. step_push(ns, cur, alloc);
  6194. cur = cur.parent();
  6195. }
  6196. break;
  6197. }
  6198. case axis_self:
  6199. {
  6200. step_push(ns, n, alloc);
  6201. break;
  6202. }
  6203. case axis_parent:
  6204. {
  6205. if (n.parent()) step_push(ns, n.parent(), alloc);
  6206. break;
  6207. }
  6208. default:
  6209. assert(!"Unimplemented axis");
  6210. }
  6211. }
  6212. template <class T> void step_fill(xpath_node_set_raw& ns, const xml_attribute& a, const xml_node& p, xpath_allocator* alloc, T v)
  6213. {
  6214. const axis_t axis = T::axis;
  6215. switch (axis)
  6216. {
  6217. case axis_ancestor:
  6218. case axis_ancestor_or_self:
  6219. {
  6220. if (axis == axis_ancestor_or_self && _test == nodetest_type_node) // reject attributes based on principal node type test
  6221. step_push(ns, a, p, alloc);
  6222. xml_node cur = p;
  6223. while (cur)
  6224. {
  6225. step_push(ns, cur, alloc);
  6226. cur = cur.parent();
  6227. }
  6228. break;
  6229. }
  6230. case axis_descendant_or_self:
  6231. case axis_self:
  6232. {
  6233. if (_test == nodetest_type_node) // reject attributes based on principal node type test
  6234. step_push(ns, a, p, alloc);
  6235. break;
  6236. }
  6237. case axis_following:
  6238. {
  6239. xml_node cur = p;
  6240. for (;;)
  6241. {
  6242. if (cur.first_child())
  6243. cur = cur.first_child();
  6244. else if (cur.next_sibling())
  6245. cur = cur.next_sibling();
  6246. else
  6247. {
  6248. while (cur && !cur.next_sibling()) cur = cur.parent();
  6249. cur = cur.next_sibling();
  6250. if (!cur) break;
  6251. }
  6252. step_push(ns, cur, alloc);
  6253. }
  6254. break;
  6255. }
  6256. case axis_parent:
  6257. {
  6258. step_push(ns, p, alloc);
  6259. break;
  6260. }
  6261. case axis_preceding:
  6262. {
  6263. // preceding:: axis does not include attribute nodes and attribute ancestors (they are the same as parent's ancestors), so we can reuse node preceding
  6264. step_fill(ns, p, alloc, v);
  6265. break;
  6266. }
  6267. default:
  6268. assert(!"Unimplemented axis");
  6269. }
  6270. }
  6271. template <class T> xpath_node_set_raw step_do(const xpath_context& c, const xpath_stack& stack, T v)
  6272. {
  6273. const axis_t axis = T::axis;
  6274. bool attributes = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_descendant_or_self || axis == axis_following || axis == axis_parent || axis == axis_preceding || axis == axis_self);
  6275. xpath_node_set_raw ns;
  6276. ns.set_type((axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_preceding || axis == axis_preceding_sibling) ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted);
  6277. if (_left)
  6278. {
  6279. xpath_node_set_raw s = _left->eval_node_set(c, stack);
  6280. // self axis preserves the original order
  6281. if (axis == axis_self) ns.set_type(s.type());
  6282. for (const xpath_node* it = s.begin(); it != s.end(); ++it)
  6283. {
  6284. size_t size = ns.size();
  6285. // in general, all axes generate elements in a particular order, but there is no order guarantee if axis is applied to two nodes
  6286. if (axis != axis_self && size != 0) ns.set_type(xpath_node_set::type_unsorted);
  6287. if (it->node())
  6288. step_fill(ns, it->node(), stack.result, v);
  6289. else if (attributes)
  6290. step_fill(ns, it->attribute(), it->parent(), stack.result, v);
  6291. apply_predicates(ns, size, stack);
  6292. }
  6293. }
  6294. else
  6295. {
  6296. if (c.n.node())
  6297. step_fill(ns, c.n.node(), stack.result, v);
  6298. else if (attributes)
  6299. step_fill(ns, c.n.attribute(), c.n.parent(), stack.result, v);
  6300. apply_predicates(ns, 0, stack);
  6301. }
  6302. // child, attribute and self axes always generate unique set of nodes
  6303. // for other axis, if the set stayed sorted, it stayed unique because the traversal algorithms do not visit the same node twice
  6304. if (axis != axis_child && axis != axis_attribute && axis != axis_self && ns.type() == xpath_node_set::type_unsorted)
  6305. ns.remove_duplicates();
  6306. return ns;
  6307. }
  6308. public:
  6309. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, const char_t* value):
  6310. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  6311. {
  6312. assert(type == ast_string_constant);
  6313. _data.string = value;
  6314. }
  6315. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, double value):
  6316. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  6317. {
  6318. assert(type == ast_number_constant);
  6319. _data.number = value;
  6320. }
  6321. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_variable* value):
  6322. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  6323. {
  6324. assert(type == ast_variable);
  6325. _data.variable = value;
  6326. }
  6327. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_ast_node* left = 0, xpath_ast_node* right = 0):
  6328. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(left), _right(right), _next(0)
  6329. {
  6330. }
  6331. xpath_ast_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents):
  6332. _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(static_cast<char>(axis)), _test(static_cast<char>(test)), _left(left), _right(0), _next(0)
  6333. {
  6334. _data.nodetest = contents;
  6335. }
  6336. void set_next(xpath_ast_node* value)
  6337. {
  6338. _next = value;
  6339. }
  6340. void set_right(xpath_ast_node* value)
  6341. {
  6342. _right = value;
  6343. }
  6344. bool eval_boolean(const xpath_context& c, const xpath_stack& stack)
  6345. {
  6346. switch (_type)
  6347. {
  6348. case ast_op_or:
  6349. return _left->eval_boolean(c, stack) || _right->eval_boolean(c, stack);
  6350. case ast_op_and:
  6351. return _left->eval_boolean(c, stack) && _right->eval_boolean(c, stack);
  6352. case ast_op_equal:
  6353. return compare_eq(_left, _right, c, stack, equal_to());
  6354. case ast_op_not_equal:
  6355. return compare_eq(_left, _right, c, stack, not_equal_to());
  6356. case ast_op_less:
  6357. return compare_rel(_left, _right, c, stack, less());
  6358. case ast_op_greater:
  6359. return compare_rel(_right, _left, c, stack, less());
  6360. case ast_op_less_or_equal:
  6361. return compare_rel(_left, _right, c, stack, less_equal());
  6362. case ast_op_greater_or_equal:
  6363. return compare_rel(_right, _left, c, stack, less_equal());
  6364. case ast_func_starts_with:
  6365. {
  6366. xpath_allocator_capture cr(stack.result);
  6367. xpath_string lr = _left->eval_string(c, stack);
  6368. xpath_string rr = _right->eval_string(c, stack);
  6369. return starts_with(lr.c_str(), rr.c_str());
  6370. }
  6371. case ast_func_contains:
  6372. {
  6373. xpath_allocator_capture cr(stack.result);
  6374. xpath_string lr = _left->eval_string(c, stack);
  6375. xpath_string rr = _right->eval_string(c, stack);
  6376. return find_substring(lr.c_str(), rr.c_str()) != 0;
  6377. }
  6378. case ast_func_boolean:
  6379. return _left->eval_boolean(c, stack);
  6380. case ast_func_not:
  6381. return !_left->eval_boolean(c, stack);
  6382. case ast_func_true:
  6383. return true;
  6384. case ast_func_false:
  6385. return false;
  6386. case ast_func_lang:
  6387. {
  6388. if (c.n.attribute()) return false;
  6389. xpath_allocator_capture cr(stack.result);
  6390. xpath_string lang = _left->eval_string(c, stack);
  6391. for (xml_node n = c.n.node(); n; n = n.parent())
  6392. {
  6393. xml_attribute a = n.attribute(PUGIXML_TEXT("xml:lang"));
  6394. if (a)
  6395. {
  6396. const char_t* value = a.value();
  6397. // strnicmp / strncasecmp is not portable
  6398. for (const char_t* lit = lang.c_str(); *lit; ++lit)
  6399. {
  6400. if (tolower_ascii(*lit) != tolower_ascii(*value)) return false;
  6401. ++value;
  6402. }
  6403. return *value == 0 || *value == '-';
  6404. }
  6405. }
  6406. return false;
  6407. }
  6408. case ast_variable:
  6409. {
  6410. assert(_rettype == _data.variable->type());
  6411. if (_rettype == xpath_type_boolean)
  6412. return _data.variable->get_boolean();
  6413. // fallthrough to type conversion
  6414. }
  6415. default:
  6416. {
  6417. switch (_rettype)
  6418. {
  6419. case xpath_type_number:
  6420. return convert_number_to_boolean(eval_number(c, stack));
  6421. case xpath_type_string:
  6422. {
  6423. xpath_allocator_capture cr(stack.result);
  6424. return !eval_string(c, stack).empty();
  6425. }
  6426. case xpath_type_node_set:
  6427. {
  6428. xpath_allocator_capture cr(stack.result);
  6429. return !eval_node_set(c, stack).empty();
  6430. }
  6431. default:
  6432. assert(!"Wrong expression for return type boolean");
  6433. return false;
  6434. }
  6435. }
  6436. }
  6437. }
  6438. double eval_number(const xpath_context& c, const xpath_stack& stack)
  6439. {
  6440. switch (_type)
  6441. {
  6442. case ast_op_add:
  6443. return _left->eval_number(c, stack) + _right->eval_number(c, stack);
  6444. case ast_op_subtract:
  6445. return _left->eval_number(c, stack) - _right->eval_number(c, stack);
  6446. case ast_op_multiply:
  6447. return _left->eval_number(c, stack) * _right->eval_number(c, stack);
  6448. case ast_op_divide:
  6449. return _left->eval_number(c, stack) / _right->eval_number(c, stack);
  6450. case ast_op_mod:
  6451. return fmod(_left->eval_number(c, stack), _right->eval_number(c, stack));
  6452. case ast_op_negate:
  6453. return -_left->eval_number(c, stack);
  6454. case ast_number_constant:
  6455. return _data.number;
  6456. case ast_func_last:
  6457. return static_cast<double>(c.size);
  6458. case ast_func_position:
  6459. return static_cast<double>(c.position);
  6460. case ast_func_count:
  6461. {
  6462. xpath_allocator_capture cr(stack.result);
  6463. return static_cast<double>(_left->eval_node_set(c, stack).size());
  6464. }
  6465. case ast_func_string_length_0:
  6466. {
  6467. xpath_allocator_capture cr(stack.result);
  6468. return static_cast<double>(string_value(c.n, stack.result).length());
  6469. }
  6470. case ast_func_string_length_1:
  6471. {
  6472. xpath_allocator_capture cr(stack.result);
  6473. return static_cast<double>(_left->eval_string(c, stack).length());
  6474. }
  6475. case ast_func_number_0:
  6476. {
  6477. xpath_allocator_capture cr(stack.result);
  6478. return convert_string_to_number(string_value(c.n, stack.result).c_str());
  6479. }
  6480. case ast_func_number_1:
  6481. return _left->eval_number(c, stack);
  6482. case ast_func_sum:
  6483. {
  6484. xpath_allocator_capture cr(stack.result);
  6485. double r = 0;
  6486. xpath_node_set_raw ns = _left->eval_node_set(c, stack);
  6487. for (const xpath_node* it = ns.begin(); it != ns.end(); ++it)
  6488. {
  6489. xpath_allocator_capture cri(stack.result);
  6490. r += convert_string_to_number(string_value(*it, stack.result).c_str());
  6491. }
  6492. return r;
  6493. }
  6494. case ast_func_floor:
  6495. {
  6496. double r = _left->eval_number(c, stack);
  6497. return r == r ? floor(r) : r;
  6498. }
  6499. case ast_func_ceiling:
  6500. {
  6501. double r = _left->eval_number(c, stack);
  6502. return r == r ? ceil(r) : r;
  6503. }
  6504. case ast_func_round:
  6505. return round_nearest_nzero(_left->eval_number(c, stack));
  6506. case ast_variable:
  6507. {
  6508. assert(_rettype == _data.variable->type());
  6509. if (_rettype == xpath_type_number)
  6510. return _data.variable->get_number();
  6511. // fallthrough to type conversion
  6512. }
  6513. default:
  6514. {
  6515. switch (_rettype)
  6516. {
  6517. case xpath_type_boolean:
  6518. return eval_boolean(c, stack) ? 1 : 0;
  6519. case xpath_type_string:
  6520. {
  6521. xpath_allocator_capture cr(stack.result);
  6522. return convert_string_to_number(eval_string(c, stack).c_str());
  6523. }
  6524. case xpath_type_node_set:
  6525. {
  6526. xpath_allocator_capture cr(stack.result);
  6527. return convert_string_to_number(eval_string(c, stack).c_str());
  6528. }
  6529. default:
  6530. assert(!"Wrong expression for return type number");
  6531. return 0;
  6532. }
  6533. }
  6534. }
  6535. }
  6536. xpath_string eval_string_concat(const xpath_context& c, const xpath_stack& stack)
  6537. {
  6538. assert(_type == ast_func_concat);
  6539. xpath_allocator_capture ct(stack.temp);
  6540. // count the string number
  6541. size_t count = 1;
  6542. for (xpath_ast_node* nc = _right; nc; nc = nc->_next) count++;
  6543. // gather all strings
  6544. xpath_string static_buffer[4];
  6545. xpath_string* buffer = static_buffer;
  6546. // allocate on-heap for large concats
  6547. if (count > sizeof(static_buffer) / sizeof(static_buffer[0]))
  6548. {
  6549. buffer = static_cast<xpath_string*>(stack.temp->allocate(count * sizeof(xpath_string)));
  6550. assert(buffer);
  6551. }
  6552. // evaluate all strings to temporary stack
  6553. xpath_stack swapped_stack = {stack.temp, stack.result};
  6554. buffer[0] = _left->eval_string(c, swapped_stack);
  6555. size_t pos = 1;
  6556. for (xpath_ast_node* n = _right; n; n = n->_next, ++pos) buffer[pos] = n->eval_string(c, swapped_stack);
  6557. assert(pos == count);
  6558. // get total length
  6559. size_t length = 0;
  6560. for (size_t i = 0; i < count; ++i) length += buffer[i].length();
  6561. // create final string
  6562. char_t* result = static_cast<char_t*>(stack.result->allocate((length + 1) * sizeof(char_t)));
  6563. assert(result);
  6564. char_t* ri = result;
  6565. for (size_t j = 0; j < count; ++j)
  6566. for (const char_t* bi = buffer[j].c_str(); *bi; ++bi)
  6567. *ri++ = *bi;
  6568. *ri = 0;
  6569. return xpath_string(result, true);
  6570. }
  6571. xpath_string eval_string(const xpath_context& c, const xpath_stack& stack)
  6572. {
  6573. switch (_type)
  6574. {
  6575. case ast_string_constant:
  6576. return xpath_string_const(_data.string);
  6577. case ast_func_local_name_0:
  6578. {
  6579. xpath_node na = c.n;
  6580. return xpath_string_const(local_name(na));
  6581. }
  6582. case ast_func_local_name_1:
  6583. {
  6584. xpath_allocator_capture cr(stack.result);
  6585. xpath_node_set_raw ns = _left->eval_node_set(c, stack);
  6586. xpath_node na = ns.first();
  6587. return xpath_string_const(local_name(na));
  6588. }
  6589. case ast_func_name_0:
  6590. {
  6591. xpath_node na = c.n;
  6592. return xpath_string_const(qualified_name(na));
  6593. }
  6594. case ast_func_name_1:
  6595. {
  6596. xpath_allocator_capture cr(stack.result);
  6597. xpath_node_set_raw ns = _left->eval_node_set(c, stack);
  6598. xpath_node na = ns.first();
  6599. return xpath_string_const(qualified_name(na));
  6600. }
  6601. case ast_func_namespace_uri_0:
  6602. {
  6603. xpath_node na = c.n;
  6604. return xpath_string_const(namespace_uri(na));
  6605. }
  6606. case ast_func_namespace_uri_1:
  6607. {
  6608. xpath_allocator_capture cr(stack.result);
  6609. xpath_node_set_raw ns = _left->eval_node_set(c, stack);
  6610. xpath_node na = ns.first();
  6611. return xpath_string_const(namespace_uri(na));
  6612. }
  6613. case ast_func_string_0:
  6614. return string_value(c.n, stack.result);
  6615. case ast_func_string_1:
  6616. return _left->eval_string(c, stack);
  6617. case ast_func_concat:
  6618. return eval_string_concat(c, stack);
  6619. case ast_func_substring_before:
  6620. {
  6621. xpath_allocator_capture cr(stack.temp);
  6622. xpath_stack swapped_stack = {stack.temp, stack.result};
  6623. xpath_string s = _left->eval_string(c, swapped_stack);
  6624. xpath_string p = _right->eval_string(c, swapped_stack);
  6625. const char_t* pos = find_substring(s.c_str(), p.c_str());
  6626. return pos ? xpath_string(s.c_str(), pos, stack.result) : xpath_string();
  6627. }
  6628. case ast_func_substring_after:
  6629. {
  6630. xpath_allocator_capture cr(stack.temp);
  6631. xpath_stack swapped_stack = {stack.temp, stack.result};
  6632. xpath_string s = _left->eval_string(c, swapped_stack);
  6633. xpath_string p = _right->eval_string(c, swapped_stack);
  6634. const char_t* pos = find_substring(s.c_str(), p.c_str());
  6635. if (!pos) return xpath_string();
  6636. const char_t* result = pos + p.length();
  6637. return s.uses_heap() ? xpath_string(result, stack.result) : xpath_string_const(result);
  6638. }
  6639. case ast_func_substring_2:
  6640. {
  6641. xpath_allocator_capture cr(stack.temp);
  6642. xpath_stack swapped_stack = {stack.temp, stack.result};
  6643. xpath_string s = _left->eval_string(c, swapped_stack);
  6644. size_t s_length = s.length();
  6645. double first = round_nearest(_right->eval_number(c, stack));
  6646. if (is_nan(first)) return xpath_string(); // NaN
  6647. else if (first >= s_length + 1) return xpath_string();
  6648. size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
  6649. assert(1 <= pos && pos <= s_length + 1);
  6650. const char_t* rbegin = s.c_str() + (pos - 1);
  6651. return s.uses_heap() ? xpath_string(rbegin, stack.result) : xpath_string_const(rbegin);
  6652. }
  6653. case ast_func_substring_3:
  6654. {
  6655. xpath_allocator_capture cr(stack.temp);
  6656. xpath_stack swapped_stack = {stack.temp, stack.result};
  6657. xpath_string s = _left->eval_string(c, swapped_stack);
  6658. size_t s_length = s.length();
  6659. double first = round_nearest(_right->eval_number(c, stack));
  6660. double last = first + round_nearest(_right->_next->eval_number(c, stack));
  6661. if (is_nan(first) || is_nan(last)) return xpath_string();
  6662. else if (first >= s_length + 1) return xpath_string();
  6663. else if (first >= last) return xpath_string();
  6664. else if (last < 1) return xpath_string();
  6665. size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
  6666. size_t end = last >= s_length + 1 ? s_length + 1 : static_cast<size_t>(last);
  6667. assert(1 <= pos && pos <= end && end <= s_length + 1);
  6668. const char_t* rbegin = s.c_str() + (pos - 1);
  6669. const char_t* rend = s.c_str() + (end - 1);
  6670. return (end == s_length + 1 && !s.uses_heap()) ? xpath_string_const(rbegin) : xpath_string(rbegin, rend, stack.result);
  6671. }
  6672. case ast_func_normalize_space_0:
  6673. {
  6674. xpath_string s = string_value(c.n, stack.result);
  6675. normalize_space(s.data(stack.result));
  6676. return s;
  6677. }
  6678. case ast_func_normalize_space_1:
  6679. {
  6680. xpath_string s = _left->eval_string(c, stack);
  6681. normalize_space(s.data(stack.result));
  6682. return s;
  6683. }
  6684. case ast_func_translate:
  6685. {
  6686. xpath_allocator_capture cr(stack.temp);
  6687. xpath_stack swapped_stack = {stack.temp, stack.result};
  6688. xpath_string s = _left->eval_string(c, stack);
  6689. xpath_string from = _right->eval_string(c, swapped_stack);
  6690. xpath_string to = _right->_next->eval_string(c, swapped_stack);
  6691. translate(s.data(stack.result), from.c_str(), to.c_str());
  6692. return s;
  6693. }
  6694. case ast_variable:
  6695. {
  6696. assert(_rettype == _data.variable->type());
  6697. if (_rettype == xpath_type_string)
  6698. return xpath_string_const(_data.variable->get_string());
  6699. // fallthrough to type conversion
  6700. }
  6701. default:
  6702. {
  6703. switch (_rettype)
  6704. {
  6705. case xpath_type_boolean:
  6706. return xpath_string_const(eval_boolean(c, stack) ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
  6707. case xpath_type_number:
  6708. return convert_number_to_string(eval_number(c, stack), stack.result);
  6709. case xpath_type_node_set:
  6710. {
  6711. xpath_allocator_capture cr(stack.temp);
  6712. xpath_stack swapped_stack = {stack.temp, stack.result};
  6713. xpath_node_set_raw ns = eval_node_set(c, swapped_stack);
  6714. return ns.empty() ? xpath_string() : string_value(ns.first(), stack.result);
  6715. }
  6716. default:
  6717. assert(!"Wrong expression for return type string");
  6718. return xpath_string();
  6719. }
  6720. }
  6721. }
  6722. }
  6723. xpath_node_set_raw eval_node_set(const xpath_context& c, const xpath_stack& stack)
  6724. {
  6725. switch (_type)
  6726. {
  6727. case ast_op_union:
  6728. {
  6729. xpath_allocator_capture cr(stack.temp);
  6730. xpath_stack swapped_stack = {stack.temp, stack.result};
  6731. xpath_node_set_raw ls = _left->eval_node_set(c, swapped_stack);
  6732. xpath_node_set_raw rs = _right->eval_node_set(c, stack);
  6733. // we can optimize merging two sorted sets, but this is a very rare operation, so don't bother
  6734. rs.set_type(xpath_node_set::type_unsorted);
  6735. rs.append(ls.begin(), ls.end(), stack.result);
  6736. rs.remove_duplicates();
  6737. return rs;
  6738. }
  6739. case ast_filter:
  6740. case ast_filter_posinv:
  6741. {
  6742. xpath_node_set_raw set = _left->eval_node_set(c, stack);
  6743. // either expression is a number or it contains position() call; sort by document order
  6744. if (_type == ast_filter) set.sort_do();
  6745. apply_predicate(set, 0, _right, stack);
  6746. return set;
  6747. }
  6748. case ast_func_id:
  6749. return xpath_node_set_raw();
  6750. case ast_step:
  6751. {
  6752. switch (_axis)
  6753. {
  6754. case axis_ancestor:
  6755. return step_do(c, stack, axis_to_type<axis_ancestor>());
  6756. case axis_ancestor_or_self:
  6757. return step_do(c, stack, axis_to_type<axis_ancestor_or_self>());
  6758. case axis_attribute:
  6759. return step_do(c, stack, axis_to_type<axis_attribute>());
  6760. case axis_child:
  6761. return step_do(c, stack, axis_to_type<axis_child>());
  6762. case axis_descendant:
  6763. return step_do(c, stack, axis_to_type<axis_descendant>());
  6764. case axis_descendant_or_self:
  6765. return step_do(c, stack, axis_to_type<axis_descendant_or_self>());
  6766. case axis_following:
  6767. return step_do(c, stack, axis_to_type<axis_following>());
  6768. case axis_following_sibling:
  6769. return step_do(c, stack, axis_to_type<axis_following_sibling>());
  6770. case axis_namespace:
  6771. // namespaced axis is not supported
  6772. return xpath_node_set_raw();
  6773. case axis_parent:
  6774. return step_do(c, stack, axis_to_type<axis_parent>());
  6775. case axis_preceding:
  6776. return step_do(c, stack, axis_to_type<axis_preceding>());
  6777. case axis_preceding_sibling:
  6778. return step_do(c, stack, axis_to_type<axis_preceding_sibling>());
  6779. case axis_self:
  6780. return step_do(c, stack, axis_to_type<axis_self>());
  6781. default:
  6782. assert(!"Unknown axis");
  6783. return xpath_node_set_raw();
  6784. }
  6785. }
  6786. case ast_step_root:
  6787. {
  6788. assert(!_right); // root step can't have any predicates
  6789. xpath_node_set_raw ns;
  6790. ns.set_type(xpath_node_set::type_sorted);
  6791. if (c.n.node()) ns.push_back(c.n.node().root(), stack.result);
  6792. else if (c.n.attribute()) ns.push_back(c.n.parent().root(), stack.result);
  6793. return ns;
  6794. }
  6795. case ast_variable:
  6796. {
  6797. assert(_rettype == _data.variable->type());
  6798. if (_rettype == xpath_type_node_set)
  6799. {
  6800. const xpath_node_set& s = _data.variable->get_node_set();
  6801. xpath_node_set_raw ns;
  6802. ns.set_type(s.type());
  6803. ns.append(s.begin(), s.end(), stack.result);
  6804. return ns;
  6805. }
  6806. // fallthrough to type conversion
  6807. }
  6808. default:
  6809. assert(!"Wrong expression for return type node set");
  6810. return xpath_node_set_raw();
  6811. }
  6812. }
  6813. bool is_posinv()
  6814. {
  6815. switch (_type)
  6816. {
  6817. case ast_func_position:
  6818. return false;
  6819. case ast_string_constant:
  6820. case ast_number_constant:
  6821. case ast_variable:
  6822. return true;
  6823. case ast_step:
  6824. case ast_step_root:
  6825. return true;
  6826. case ast_predicate:
  6827. case ast_filter:
  6828. case ast_filter_posinv:
  6829. return true;
  6830. default:
  6831. if (_left && !_left->is_posinv()) return false;
  6832. for (xpath_ast_node* n = _right; n; n = n->_next)
  6833. if (!n->is_posinv()) return false;
  6834. return true;
  6835. }
  6836. }
  6837. xpath_value_type rettype() const
  6838. {
  6839. return static_cast<xpath_value_type>(_rettype);
  6840. }
  6841. };
  6842. struct xpath_parser
  6843. {
  6844. xpath_allocator* _alloc;
  6845. xpath_lexer _lexer;
  6846. const char_t* _query;
  6847. xpath_variable_set* _variables;
  6848. xpath_parse_result* _result;
  6849. #ifdef PUGIXML_NO_EXCEPTIONS
  6850. jmp_buf _error_handler;
  6851. #endif
  6852. void throw_error(const char* message)
  6853. {
  6854. _result->error = message;
  6855. _result->offset = _lexer.current_pos() - _query;
  6856. #ifdef PUGIXML_NO_EXCEPTIONS
  6857. longjmp(_error_handler, 1);
  6858. #else
  6859. throw xpath_exception(*_result);
  6860. #endif
  6861. }
  6862. void throw_error_oom()
  6863. {
  6864. #ifdef PUGIXML_NO_EXCEPTIONS
  6865. throw_error("Out of memory");
  6866. #else
  6867. throw std::bad_alloc();
  6868. #endif
  6869. }
  6870. void* alloc_node()
  6871. {
  6872. void* result = _alloc->allocate_nothrow(sizeof(xpath_ast_node));
  6873. if (!result) throw_error_oom();
  6874. return result;
  6875. }
  6876. const char_t* alloc_string(const xpath_lexer_string& value)
  6877. {
  6878. if (value.begin)
  6879. {
  6880. size_t length = static_cast<size_t>(value.end - value.begin);
  6881. char_t* c = static_cast<char_t*>(_alloc->allocate_nothrow((length + 1) * sizeof(char_t)));
  6882. if (!c) throw_error_oom();
  6883. memcpy(c, value.begin, length * sizeof(char_t));
  6884. c[length] = 0;
  6885. return c;
  6886. }
  6887. else return 0;
  6888. }
  6889. xpath_ast_node* parse_function_helper(ast_type_t type0, ast_type_t type1, size_t argc, xpath_ast_node* args[2])
  6890. {
  6891. assert(argc <= 1);
  6892. if (argc == 1 && args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");
  6893. return new (alloc_node()) xpath_ast_node(argc == 0 ? type0 : type1, xpath_type_string, args[0]);
  6894. }
  6895. xpath_ast_node* parse_function(const xpath_lexer_string& name, size_t argc, xpath_ast_node* args[2])
  6896. {
  6897. switch (name.begin[0])
  6898. {
  6899. case 'b':
  6900. if (name == PUGIXML_TEXT("boolean") && argc == 1)
  6901. return new (alloc_node()) xpath_ast_node(ast_func_boolean, xpath_type_boolean, args[0]);
  6902. break;
  6903. case 'c':
  6904. if (name == PUGIXML_TEXT("count") && argc == 1)
  6905. {
  6906. if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");
  6907. return new (alloc_node()) xpath_ast_node(ast_func_count, xpath_type_number, args[0]);
  6908. }
  6909. else if (name == PUGIXML_TEXT("contains") && argc == 2)
  6910. return new (alloc_node()) xpath_ast_node(ast_func_contains, xpath_type_string, args[0], args[1]);
  6911. else if (name == PUGIXML_TEXT("concat") && argc >= 2)
  6912. return new (alloc_node()) xpath_ast_node(ast_func_concat, xpath_type_string, args[0], args[1]);
  6913. else if (name == PUGIXML_TEXT("ceiling") && argc == 1)
  6914. return new (alloc_node()) xpath_ast_node(ast_func_ceiling, xpath_type_number, args[0]);
  6915. break;
  6916. case 'f':
  6917. if (name == PUGIXML_TEXT("false") && argc == 0)
  6918. return new (alloc_node()) xpath_ast_node(ast_func_false, xpath_type_boolean);
  6919. else if (name == PUGIXML_TEXT("floor") && argc == 1)
  6920. return new (alloc_node()) xpath_ast_node(ast_func_floor, xpath_type_number, args[0]);
  6921. break;
  6922. case 'i':
  6923. if (name == PUGIXML_TEXT("id") && argc == 1)
  6924. return new (alloc_node()) xpath_ast_node(ast_func_id, xpath_type_node_set, args[0]);
  6925. break;
  6926. case 'l':
  6927. if (name == PUGIXML_TEXT("last") && argc == 0)
  6928. return new (alloc_node()) xpath_ast_node(ast_func_last, xpath_type_number);
  6929. else if (name == PUGIXML_TEXT("lang") && argc == 1)
  6930. return new (alloc_node()) xpath_ast_node(ast_func_lang, xpath_type_boolean, args[0]);
  6931. else if (name == PUGIXML_TEXT("local-name") && argc <= 1)
  6932. return parse_function_helper(ast_func_local_name_0, ast_func_local_name_1, argc, args);
  6933. break;
  6934. case 'n':
  6935. if (name == PUGIXML_TEXT("name") && argc <= 1)
  6936. return parse_function_helper(ast_func_name_0, ast_func_name_1, argc, args);
  6937. else if (name == PUGIXML_TEXT("namespace-uri") && argc <= 1)
  6938. return parse_function_helper(ast_func_namespace_uri_0, ast_func_namespace_uri_1, argc, args);
  6939. else if (name == PUGIXML_TEXT("normalize-space") && argc <= 1)
  6940. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_normalize_space_0 : ast_func_normalize_space_1, xpath_type_string, args[0], args[1]);
  6941. else if (name == PUGIXML_TEXT("not") && argc == 1)
  6942. return new (alloc_node()) xpath_ast_node(ast_func_not, xpath_type_boolean, args[0]);
  6943. else if (name == PUGIXML_TEXT("number") && argc <= 1)
  6944. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_number_0 : ast_func_number_1, xpath_type_number, args[0]);
  6945. break;
  6946. case 'p':
  6947. if (name == PUGIXML_TEXT("position") && argc == 0)
  6948. return new (alloc_node()) xpath_ast_node(ast_func_position, xpath_type_number);
  6949. break;
  6950. case 'r':
  6951. if (name == PUGIXML_TEXT("round") && argc == 1)
  6952. return new (alloc_node()) xpath_ast_node(ast_func_round, xpath_type_number, args[0]);
  6953. break;
  6954. case 's':
  6955. if (name == PUGIXML_TEXT("string") && argc <= 1)
  6956. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_0 : ast_func_string_1, xpath_type_string, args[0]);
  6957. else if (name == PUGIXML_TEXT("string-length") && argc <= 1)
  6958. return new (alloc_node()) xpath_ast_node(argc == 0 ? ast_func_string_length_0 : ast_func_string_length_1, xpath_type_string, args[0]);
  6959. else if (name == PUGIXML_TEXT("starts-with") && argc == 2)
  6960. return new (alloc_node()) xpath_ast_node(ast_func_starts_with, xpath_type_boolean, args[0], args[1]);
  6961. else if (name == PUGIXML_TEXT("substring-before") && argc == 2)
  6962. return new (alloc_node()) xpath_ast_node(ast_func_substring_before, xpath_type_string, args[0], args[1]);
  6963. else if (name == PUGIXML_TEXT("substring-after") && argc == 2)
  6964. return new (alloc_node()) xpath_ast_node(ast_func_substring_after, xpath_type_string, args[0], args[1]);
  6965. else if (name == PUGIXML_TEXT("substring") && (argc == 2 || argc == 3))
  6966. return new (alloc_node()) xpath_ast_node(argc == 2 ? ast_func_substring_2 : ast_func_substring_3, xpath_type_string, args[0], args[1]);
  6967. else if (name == PUGIXML_TEXT("sum") && argc == 1)
  6968. {
  6969. if (args[0]->rettype() != xpath_type_node_set) throw_error("Function has to be applied to node set");
  6970. return new (alloc_node()) xpath_ast_node(ast_func_sum, xpath_type_number, args[0]);
  6971. }
  6972. break;
  6973. case 't':
  6974. if (name == PUGIXML_TEXT("translate") && argc == 3)
  6975. return new (alloc_node()) xpath_ast_node(ast_func_translate, xpath_type_string, args[0], args[1]);
  6976. else if (name == PUGIXML_TEXT("true") && argc == 0)
  6977. return new (alloc_node()) xpath_ast_node(ast_func_true, xpath_type_boolean);
  6978. break;
  6979. default:
  6980. break;
  6981. }
  6982. throw_error("Unrecognized function or wrong parameter count");
  6983. return 0;
  6984. }
  6985. axis_t parse_axis_name(const xpath_lexer_string& name, bool& specified)
  6986. {
  6987. specified = true;
  6988. switch (name.begin[0])
  6989. {
  6990. case 'a':
  6991. if (name == PUGIXML_TEXT("ancestor"))
  6992. return axis_ancestor;
  6993. else if (name == PUGIXML_TEXT("ancestor-or-self"))
  6994. return axis_ancestor_or_self;
  6995. else if (name == PUGIXML_TEXT("attribute"))
  6996. return axis_attribute;
  6997. break;
  6998. case 'c':
  6999. if (name == PUGIXML_TEXT("child"))
  7000. return axis_child;
  7001. break;
  7002. case 'd':
  7003. if (name == PUGIXML_TEXT("descendant"))
  7004. return axis_descendant;
  7005. else if (name == PUGIXML_TEXT("descendant-or-self"))
  7006. return axis_descendant_or_self;
  7007. break;
  7008. case 'f':
  7009. if (name == PUGIXML_TEXT("following"))
  7010. return axis_following;
  7011. else if (name == PUGIXML_TEXT("following-sibling"))
  7012. return axis_following_sibling;
  7013. break;
  7014. case 'n':
  7015. if (name == PUGIXML_TEXT("namespace"))
  7016. return axis_namespace;
  7017. break;
  7018. case 'p':
  7019. if (name == PUGIXML_TEXT("parent"))
  7020. return axis_parent;
  7021. else if (name == PUGIXML_TEXT("preceding"))
  7022. return axis_preceding;
  7023. else if (name == PUGIXML_TEXT("preceding-sibling"))
  7024. return axis_preceding_sibling;
  7025. break;
  7026. case 's':
  7027. if (name == PUGIXML_TEXT("self"))
  7028. return axis_self;
  7029. break;
  7030. default:
  7031. break;
  7032. }
  7033. specified = false;
  7034. return axis_child;
  7035. }
  7036. nodetest_t parse_node_test_type(const xpath_lexer_string& name)
  7037. {
  7038. switch (name.begin[0])
  7039. {
  7040. case 'c':
  7041. if (name == PUGIXML_TEXT("comment"))
  7042. return nodetest_type_comment;
  7043. break;
  7044. case 'n':
  7045. if (name == PUGIXML_TEXT("node"))
  7046. return nodetest_type_node;
  7047. break;
  7048. case 'p':
  7049. if (name == PUGIXML_TEXT("processing-instruction"))
  7050. return nodetest_type_pi;
  7051. break;
  7052. case 't':
  7053. if (name == PUGIXML_TEXT("text"))
  7054. return nodetest_type_text;
  7055. break;
  7056. default:
  7057. break;
  7058. }
  7059. return nodetest_none;
  7060. }
  7061. // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
  7062. xpath_ast_node* parse_primary_expression()
  7063. {
  7064. switch (_lexer.current())
  7065. {
  7066. case lex_var_ref:
  7067. {
  7068. xpath_lexer_string name = _lexer.contents();
  7069. if (!_variables)
  7070. throw_error("Unknown variable: variable set is not provided");
  7071. xpath_variable* var = get_variable(_variables, name.begin, name.end);
  7072. if (!var)
  7073. throw_error("Unknown variable: variable set does not contain the given name");
  7074. _lexer.next();
  7075. return new (alloc_node()) xpath_ast_node(ast_variable, var->type(), var);
  7076. }
  7077. case lex_open_brace:
  7078. {
  7079. _lexer.next();
  7080. xpath_ast_node* n = parse_expression();
  7081. if (_lexer.current() != lex_close_brace)
  7082. throw_error("Unmatched braces");
  7083. _lexer.next();
  7084. return n;
  7085. }
  7086. case lex_quoted_string:
  7087. {
  7088. const char_t* value = alloc_string(_lexer.contents());
  7089. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_string_constant, xpath_type_string, value);
  7090. _lexer.next();
  7091. return n;
  7092. }
  7093. case lex_number:
  7094. {
  7095. double value = 0;
  7096. if (!convert_string_to_number(_lexer.contents().begin, _lexer.contents().end, &value))
  7097. throw_error_oom();
  7098. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_number_constant, xpath_type_number, value);
  7099. _lexer.next();
  7100. return n;
  7101. }
  7102. case lex_string:
  7103. {
  7104. xpath_ast_node* args[2] = {0};
  7105. size_t argc = 0;
  7106. xpath_lexer_string function = _lexer.contents();
  7107. _lexer.next();
  7108. xpath_ast_node* last_arg = 0;
  7109. if (_lexer.current() != lex_open_brace)
  7110. throw_error("Unrecognized function call");
  7111. _lexer.next();
  7112. if (_lexer.current() != lex_close_brace)
  7113. args[argc++] = parse_expression();
  7114. while (_lexer.current() != lex_close_brace)
  7115. {
  7116. if (_lexer.current() != lex_comma)
  7117. throw_error("No comma between function arguments");
  7118. _lexer.next();
  7119. xpath_ast_node* n = parse_expression();
  7120. if (argc < 2) args[argc] = n;
  7121. else last_arg->set_next(n);
  7122. argc++;
  7123. last_arg = n;
  7124. }
  7125. _lexer.next();
  7126. return parse_function(function, argc, args);
  7127. }
  7128. default:
  7129. throw_error("Unrecognizable primary expression");
  7130. return 0;
  7131. }
  7132. }
  7133. // FilterExpr ::= PrimaryExpr | FilterExpr Predicate
  7134. // Predicate ::= '[' PredicateExpr ']'
  7135. // PredicateExpr ::= Expr
  7136. xpath_ast_node* parse_filter_expression()
  7137. {
  7138. xpath_ast_node* n = parse_primary_expression();
  7139. while (_lexer.current() == lex_open_square_brace)
  7140. {
  7141. _lexer.next();
  7142. xpath_ast_node* expr = parse_expression();
  7143. if (n->rettype() != xpath_type_node_set) throw_error("Predicate has to be applied to node set");
  7144. bool posinv = expr->rettype() != xpath_type_number && expr->is_posinv();
  7145. n = new (alloc_node()) xpath_ast_node(posinv ? ast_filter_posinv : ast_filter, xpath_type_node_set, n, expr);
  7146. if (_lexer.current() != lex_close_square_brace)
  7147. throw_error("Unmatched square brace");
  7148. _lexer.next();
  7149. }
  7150. return n;
  7151. }
  7152. // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
  7153. // AxisSpecifier ::= AxisName '::' | '@'?
  7154. // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'
  7155. // NameTest ::= '*' | NCName ':' '*' | QName
  7156. // AbbreviatedStep ::= '.' | '..'
  7157. xpath_ast_node* parse_step(xpath_ast_node* set)
  7158. {
  7159. if (set && set->rettype() != xpath_type_node_set)
  7160. throw_error("Step has to be applied to node set");
  7161. bool axis_specified = false;
  7162. axis_t axis = axis_child; // implied child axis
  7163. if (_lexer.current() == lex_axis_attribute)
  7164. {
  7165. axis = axis_attribute;
  7166. axis_specified = true;
  7167. _lexer.next();
  7168. }
  7169. else if (_lexer.current() == lex_dot)
  7170. {
  7171. _lexer.next();
  7172. return new (alloc_node()) xpath_ast_node(ast_step, set, axis_self, nodetest_type_node, 0);
  7173. }
  7174. else if (_lexer.current() == lex_double_dot)
  7175. {
  7176. _lexer.next();
  7177. return new (alloc_node()) xpath_ast_node(ast_step, set, axis_parent, nodetest_type_node, 0);
  7178. }
  7179. nodetest_t nt_type = nodetest_none;
  7180. xpath_lexer_string nt_name;
  7181. if (_lexer.current() == lex_string)
  7182. {
  7183. // node name test
  7184. nt_name = _lexer.contents();
  7185. _lexer.next();
  7186. // was it an axis name?
  7187. if (_lexer.current() == lex_double_colon)
  7188. {
  7189. // parse axis name
  7190. if (axis_specified) throw_error("Two axis specifiers in one step");
  7191. axis = parse_axis_name(nt_name, axis_specified);
  7192. if (!axis_specified) throw_error("Unknown axis");
  7193. // read actual node test
  7194. _lexer.next();
  7195. if (_lexer.current() == lex_multiply)
  7196. {
  7197. nt_type = nodetest_all;
  7198. nt_name = xpath_lexer_string();
  7199. _lexer.next();
  7200. }
  7201. else if (_lexer.current() == lex_string)
  7202. {
  7203. nt_name = _lexer.contents();
  7204. _lexer.next();
  7205. }
  7206. else throw_error("Unrecognized node test");
  7207. }
  7208. if (nt_type == nodetest_none)
  7209. {
  7210. // node type test or processing-instruction
  7211. if (_lexer.current() == lex_open_brace)
  7212. {
  7213. _lexer.next();
  7214. if (_lexer.current() == lex_close_brace)
  7215. {
  7216. _lexer.next();
  7217. nt_type = parse_node_test_type(nt_name);
  7218. if (nt_type == nodetest_none) throw_error("Unrecognized node type");
  7219. nt_name = xpath_lexer_string();
  7220. }
  7221. else if (nt_name == PUGIXML_TEXT("processing-instruction"))
  7222. {
  7223. if (_lexer.current() != lex_quoted_string)
  7224. throw_error("Only literals are allowed as arguments to processing-instruction()");
  7225. nt_type = nodetest_pi;
  7226. nt_name = _lexer.contents();
  7227. _lexer.next();
  7228. if (_lexer.current() != lex_close_brace)
  7229. throw_error("Unmatched brace near processing-instruction()");
  7230. _lexer.next();
  7231. }
  7232. else
  7233. throw_error("Unmatched brace near node type test");
  7234. }
  7235. // QName or NCName:*
  7236. else
  7237. {
  7238. if (nt_name.end - nt_name.begin > 2 && nt_name.end[-2] == ':' && nt_name.end[-1] == '*') // NCName:*
  7239. {
  7240. nt_name.end--; // erase *
  7241. nt_type = nodetest_all_in_namespace;
  7242. }
  7243. else nt_type = nodetest_name;
  7244. }
  7245. }
  7246. }
  7247. else if (_lexer.current() == lex_multiply)
  7248. {
  7249. nt_type = nodetest_all;
  7250. _lexer.next();
  7251. }
  7252. else throw_error("Unrecognized node test");
  7253. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step, set, axis, nt_type, alloc_string(nt_name));
  7254. xpath_ast_node* last = 0;
  7255. while (_lexer.current() == lex_open_square_brace)
  7256. {
  7257. _lexer.next();
  7258. xpath_ast_node* expr = parse_expression();
  7259. xpath_ast_node* pred = new (alloc_node()) xpath_ast_node(ast_predicate, xpath_type_node_set, expr);
  7260. if (_lexer.current() != lex_close_square_brace)
  7261. throw_error("Unmatched square brace");
  7262. _lexer.next();
  7263. if (last) last->set_next(pred);
  7264. else n->set_right(pred);
  7265. last = pred;
  7266. }
  7267. return n;
  7268. }
  7269. // RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
  7270. xpath_ast_node* parse_relative_location_path(xpath_ast_node* set)
  7271. {
  7272. xpath_ast_node* n = parse_step(set);
  7273. while (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
  7274. {
  7275. lexeme_t l = _lexer.current();
  7276. _lexer.next();
  7277. if (l == lex_double_slash)
  7278. n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  7279. n = parse_step(n);
  7280. }
  7281. return n;
  7282. }
  7283. // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
  7284. // AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
  7285. xpath_ast_node* parse_location_path()
  7286. {
  7287. if (_lexer.current() == lex_slash)
  7288. {
  7289. _lexer.next();
  7290. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set);
  7291. // relative location path can start from axis_attribute, dot, double_dot, multiply and string lexemes; any other lexeme means standalone root path
  7292. lexeme_t l = _lexer.current();
  7293. if (l == lex_string || l == lex_axis_attribute || l == lex_dot || l == lex_double_dot || l == lex_multiply)
  7294. return parse_relative_location_path(n);
  7295. else
  7296. return n;
  7297. }
  7298. else if (_lexer.current() == lex_double_slash)
  7299. {
  7300. _lexer.next();
  7301. xpath_ast_node* n = new (alloc_node()) xpath_ast_node(ast_step_root, xpath_type_node_set);
  7302. n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  7303. return parse_relative_location_path(n);
  7304. }
  7305. // else clause moved outside of if because of bogus warning 'control may reach end of non-void function being inlined' in gcc 4.0.1
  7306. return parse_relative_location_path(0);
  7307. }
  7308. // PathExpr ::= LocationPath
  7309. // | FilterExpr
  7310. // | FilterExpr '/' RelativeLocationPath
  7311. // | FilterExpr '//' RelativeLocationPath
  7312. xpath_ast_node* parse_path_expression()
  7313. {
  7314. // Clarification.
  7315. // PathExpr begins with either LocationPath or FilterExpr.
  7316. // FilterExpr begins with PrimaryExpr
  7317. // PrimaryExpr begins with '$' in case of it being a variable reference,
  7318. // '(' in case of it being an expression, string literal, number constant or
  7319. // function call.
  7320. if (_lexer.current() == lex_var_ref || _lexer.current() == lex_open_brace ||
  7321. _lexer.current() == lex_quoted_string || _lexer.current() == lex_number ||
  7322. _lexer.current() == lex_string)
  7323. {
  7324. if (_lexer.current() == lex_string)
  7325. {
  7326. // This is either a function call, or not - if not, we shall proceed with location path
  7327. const char_t* state = _lexer.state();
  7328. while (PUGI__IS_CHARTYPE(*state, ct_space)) ++state;
  7329. if (*state != '(') return parse_location_path();
  7330. // This looks like a function call; however this still can be a node-test. Check it.
  7331. if (parse_node_test_type(_lexer.contents()) != nodetest_none) return parse_location_path();
  7332. }
  7333. xpath_ast_node* n = parse_filter_expression();
  7334. if (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
  7335. {
  7336. lexeme_t l = _lexer.current();
  7337. _lexer.next();
  7338. if (l == lex_double_slash)
  7339. {
  7340. if (n->rettype() != xpath_type_node_set) throw_error("Step has to be applied to node set");
  7341. n = new (alloc_node()) xpath_ast_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  7342. }
  7343. // select from location path
  7344. return parse_relative_location_path(n);
  7345. }
  7346. return n;
  7347. }
  7348. else return parse_location_path();
  7349. }
  7350. // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
  7351. xpath_ast_node* parse_union_expression()
  7352. {
  7353. xpath_ast_node* n = parse_path_expression();
  7354. while (_lexer.current() == lex_union)
  7355. {
  7356. _lexer.next();
  7357. xpath_ast_node* expr = parse_union_expression();
  7358. if (n->rettype() != xpath_type_node_set || expr->rettype() != xpath_type_node_set)
  7359. throw_error("Union operator has to be applied to node sets");
  7360. n = new (alloc_node()) xpath_ast_node(ast_op_union, xpath_type_node_set, n, expr);
  7361. }
  7362. return n;
  7363. }
  7364. // UnaryExpr ::= UnionExpr | '-' UnaryExpr
  7365. xpath_ast_node* parse_unary_expression()
  7366. {
  7367. if (_lexer.current() == lex_minus)
  7368. {
  7369. _lexer.next();
  7370. xpath_ast_node* expr = parse_unary_expression();
  7371. return new (alloc_node()) xpath_ast_node(ast_op_negate, xpath_type_number, expr);
  7372. }
  7373. else return parse_union_expression();
  7374. }
  7375. // MultiplicativeExpr ::= UnaryExpr
  7376. // | MultiplicativeExpr '*' UnaryExpr
  7377. // | MultiplicativeExpr 'div' UnaryExpr
  7378. // | MultiplicativeExpr 'mod' UnaryExpr
  7379. xpath_ast_node* parse_multiplicative_expression()
  7380. {
  7381. xpath_ast_node* n = parse_unary_expression();
  7382. while (_lexer.current() == lex_multiply || (_lexer.current() == lex_string &&
  7383. (_lexer.contents() == PUGIXML_TEXT("mod") || _lexer.contents() == PUGIXML_TEXT("div"))))
  7384. {
  7385. ast_type_t op = _lexer.current() == lex_multiply ? ast_op_multiply :
  7386. _lexer.contents().begin[0] == 'd' ? ast_op_divide : ast_op_mod;
  7387. _lexer.next();
  7388. xpath_ast_node* expr = parse_unary_expression();
  7389. n = new (alloc_node()) xpath_ast_node(op, xpath_type_number, n, expr);
  7390. }
  7391. return n;
  7392. }
  7393. // AdditiveExpr ::= MultiplicativeExpr
  7394. // | AdditiveExpr '+' MultiplicativeExpr
  7395. // | AdditiveExpr '-' MultiplicativeExpr
  7396. xpath_ast_node* parse_additive_expression()
  7397. {
  7398. xpath_ast_node* n = parse_multiplicative_expression();
  7399. while (_lexer.current() == lex_plus || _lexer.current() == lex_minus)
  7400. {
  7401. lexeme_t l = _lexer.current();
  7402. _lexer.next();
  7403. xpath_ast_node* expr = parse_multiplicative_expression();
  7404. n = new (alloc_node()) xpath_ast_node(l == lex_plus ? ast_op_add : ast_op_subtract, xpath_type_number, n, expr);
  7405. }
  7406. return n;
  7407. }
  7408. // RelationalExpr ::= AdditiveExpr
  7409. // | RelationalExpr '<' AdditiveExpr
  7410. // | RelationalExpr '>' AdditiveExpr
  7411. // | RelationalExpr '<=' AdditiveExpr
  7412. // | RelationalExpr '>=' AdditiveExpr
  7413. xpath_ast_node* parse_relational_expression()
  7414. {
  7415. xpath_ast_node* n = parse_additive_expression();
  7416. while (_lexer.current() == lex_less || _lexer.current() == lex_less_or_equal ||
  7417. _lexer.current() == lex_greater || _lexer.current() == lex_greater_or_equal)
  7418. {
  7419. lexeme_t l = _lexer.current();
  7420. _lexer.next();
  7421. xpath_ast_node* expr = parse_additive_expression();
  7422. n = new (alloc_node()) xpath_ast_node(l == lex_less ? ast_op_less : l == lex_greater ? ast_op_greater :
  7423. l == lex_less_or_equal ? ast_op_less_or_equal : ast_op_greater_or_equal, xpath_type_boolean, n, expr);
  7424. }
  7425. return n;
  7426. }
  7427. // EqualityExpr ::= RelationalExpr
  7428. // | EqualityExpr '=' RelationalExpr
  7429. // | EqualityExpr '!=' RelationalExpr
  7430. xpath_ast_node* parse_equality_expression()
  7431. {
  7432. xpath_ast_node* n = parse_relational_expression();
  7433. while (_lexer.current() == lex_equal || _lexer.current() == lex_not_equal)
  7434. {
  7435. lexeme_t l = _lexer.current();
  7436. _lexer.next();
  7437. xpath_ast_node* expr = parse_relational_expression();
  7438. n = new (alloc_node()) xpath_ast_node(l == lex_equal ? ast_op_equal : ast_op_not_equal, xpath_type_boolean, n, expr);
  7439. }
  7440. return n;
  7441. }
  7442. // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
  7443. xpath_ast_node* parse_and_expression()
  7444. {
  7445. xpath_ast_node* n = parse_equality_expression();
  7446. while (_lexer.current() == lex_string && _lexer.contents() == PUGIXML_TEXT("and"))
  7447. {
  7448. _lexer.next();
  7449. xpath_ast_node* expr = parse_equality_expression();
  7450. n = new (alloc_node()) xpath_ast_node(ast_op_and, xpath_type_boolean, n, expr);
  7451. }
  7452. return n;
  7453. }
  7454. // OrExpr ::= AndExpr | OrExpr 'or' AndExpr
  7455. xpath_ast_node* parse_or_expression()
  7456. {
  7457. xpath_ast_node* n = parse_and_expression();
  7458. while (_lexer.current() == lex_string && _lexer.contents() == PUGIXML_TEXT("or"))
  7459. {
  7460. _lexer.next();
  7461. xpath_ast_node* expr = parse_and_expression();
  7462. n = new (alloc_node()) xpath_ast_node(ast_op_or, xpath_type_boolean, n, expr);
  7463. }
  7464. return n;
  7465. }
  7466. // Expr ::= OrExpr
  7467. xpath_ast_node* parse_expression()
  7468. {
  7469. return parse_or_expression();
  7470. }
  7471. xpath_parser(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result): _alloc(alloc), _lexer(query), _query(query), _variables(variables), _result(result)
  7472. {
  7473. }
  7474. xpath_ast_node* parse()
  7475. {
  7476. xpath_ast_node* result = parse_expression();
  7477. if (_lexer.current() != lex_eof)
  7478. {
  7479. // there are still unparsed tokens left, error
  7480. throw_error("Incorrect query");
  7481. }
  7482. return result;
  7483. }
  7484. static xpath_ast_node* parse(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result)
  7485. {
  7486. xpath_parser parser(query, variables, alloc, result);
  7487. #ifdef PUGIXML_NO_EXCEPTIONS
  7488. int error = setjmp(parser._error_handler);
  7489. return (error == 0) ? parser.parse() : 0;
  7490. #else
  7491. return parser.parse();
  7492. #endif
  7493. }
  7494. };
  7495. struct xpath_query_impl
  7496. {
  7497. static xpath_query_impl* create()
  7498. {
  7499. void* memory = xml_memory::allocate(sizeof(xpath_query_impl));
  7500. return new (memory) xpath_query_impl();
  7501. }
  7502. static void destroy(void* ptr)
  7503. {
  7504. if (!ptr) return;
  7505. // free all allocated pages
  7506. static_cast<xpath_query_impl*>(ptr)->alloc.release();
  7507. // free allocator memory (with the first page)
  7508. xml_memory::deallocate(ptr);
  7509. }
  7510. xpath_query_impl(): root(0), alloc(&block)
  7511. {
  7512. block.next = 0;
  7513. }
  7514. xpath_ast_node* root;
  7515. xpath_allocator alloc;
  7516. xpath_memory_block block;
  7517. };
  7518. PUGI__FN xpath_string evaluate_string_impl(xpath_query_impl* impl, const xpath_node& n, xpath_stack_data& sd)
  7519. {
  7520. if (!impl) return xpath_string();
  7521. #ifdef PUGIXML_NO_EXCEPTIONS
  7522. if (setjmp(sd.error_handler)) return xpath_string();
  7523. #endif
  7524. xpath_context c(n, 1, 1);
  7525. return impl->root->eval_string(c, sd.stack);
  7526. }
  7527. PUGI__NS_END
  7528. namespace pugi
  7529. {
  7530. #ifndef PUGIXML_NO_EXCEPTIONS
  7531. PUGI__FN xpath_exception::xpath_exception(const xpath_parse_result& result_): _result(result_)
  7532. {
  7533. assert(_result.error);
  7534. }
  7535. PUGI__FN const char* xpath_exception::what() const throw()
  7536. {
  7537. return _result.error;
  7538. }
  7539. PUGI__FN const xpath_parse_result& xpath_exception::result() const
  7540. {
  7541. return _result;
  7542. }
  7543. #endif
  7544. PUGI__FN xpath_node::xpath_node()
  7545. {
  7546. }
  7547. PUGI__FN xpath_node::xpath_node(const xml_node& node_): _node(node_)
  7548. {
  7549. }
  7550. PUGI__FN xpath_node::xpath_node(const xml_attribute& attribute_, const xml_node& parent_): _node(attribute_ ? parent_ : xml_node()), _attribute(attribute_)
  7551. {
  7552. }
  7553. PUGI__FN xml_node xpath_node::node() const
  7554. {
  7555. return _attribute ? xml_node() : _node;
  7556. }
  7557. PUGI__FN xml_attribute xpath_node::attribute() const
  7558. {
  7559. return _attribute;
  7560. }
  7561. PUGI__FN xml_node xpath_node::parent() const
  7562. {
  7563. return _attribute ? _node : _node.parent();
  7564. }
  7565. PUGI__FN static void unspecified_bool_xpath_node(xpath_node***)
  7566. {
  7567. }
  7568. PUGI__FN xpath_node::operator xpath_node::unspecified_bool_type() const
  7569. {
  7570. return (_node || _attribute) ? unspecified_bool_xpath_node : 0;
  7571. }
  7572. PUGI__FN bool xpath_node::operator!() const
  7573. {
  7574. return !(_node || _attribute);
  7575. }
  7576. PUGI__FN bool xpath_node::operator==(const xpath_node& n) const
  7577. {
  7578. return _node == n._node && _attribute == n._attribute;
  7579. }
  7580. PUGI__FN bool xpath_node::operator!=(const xpath_node& n) const
  7581. {
  7582. return _node != n._node || _attribute != n._attribute;
  7583. }
  7584. #ifdef __BORLANDC__
  7585. PUGI__FN bool operator&&(const xpath_node& lhs, bool rhs)
  7586. {
  7587. return (bool)lhs && rhs;
  7588. }
  7589. PUGI__FN bool operator||(const xpath_node& lhs, bool rhs)
  7590. {
  7591. return (bool)lhs || rhs;
  7592. }
  7593. #endif
  7594. PUGI__FN void xpath_node_set::_assign(const_iterator begin_, const_iterator end_)
  7595. {
  7596. assert(begin_ <= end_);
  7597. size_t size_ = static_cast<size_t>(end_ - begin_);
  7598. if (size_ <= 1)
  7599. {
  7600. // deallocate old buffer
  7601. if (_begin != &_storage) impl::xml_memory::deallocate(_begin);
  7602. // use internal buffer
  7603. if (begin_ != end_) _storage = *begin_;
  7604. _begin = &_storage;
  7605. _end = &_storage + size_;
  7606. }
  7607. else
  7608. {
  7609. // make heap copy
  7610. xpath_node* storage = static_cast<xpath_node*>(impl::xml_memory::allocate(size_ * sizeof(xpath_node)));
  7611. if (!storage)
  7612. {
  7613. #ifdef PUGIXML_NO_EXCEPTIONS
  7614. return;
  7615. #else
  7616. throw std::bad_alloc();
  7617. #endif
  7618. }
  7619. memcpy(storage, begin_, size_ * sizeof(xpath_node));
  7620. // deallocate old buffer
  7621. if (_begin != &_storage) impl::xml_memory::deallocate(_begin);
  7622. // finalize
  7623. _begin = storage;
  7624. _end = storage + size_;
  7625. }
  7626. }
  7627. PUGI__FN xpath_node_set::xpath_node_set(): _type(type_unsorted), _begin(&_storage), _end(&_storage)
  7628. {
  7629. }
  7630. PUGI__FN xpath_node_set::xpath_node_set(const_iterator begin_, const_iterator end_, type_t type_): _type(type_), _begin(&_storage), _end(&_storage)
  7631. {
  7632. _assign(begin_, end_);
  7633. }
  7634. PUGI__FN xpath_node_set::~xpath_node_set()
  7635. {
  7636. if (_begin != &_storage) impl::xml_memory::deallocate(_begin);
  7637. }
  7638. PUGI__FN xpath_node_set::xpath_node_set(const xpath_node_set& ns): _type(ns._type), _begin(&_storage), _end(&_storage)
  7639. {
  7640. _assign(ns._begin, ns._end);
  7641. }
  7642. PUGI__FN xpath_node_set& xpath_node_set::operator=(const xpath_node_set& ns)
  7643. {
  7644. if (this == &ns) return *this;
  7645. _type = ns._type;
  7646. _assign(ns._begin, ns._end);
  7647. return *this;
  7648. }
  7649. PUGI__FN xpath_node_set::type_t xpath_node_set::type() const
  7650. {
  7651. return _type;
  7652. }
  7653. PUGI__FN size_t xpath_node_set::size() const
  7654. {
  7655. return _end - _begin;
  7656. }
  7657. PUGI__FN bool xpath_node_set::empty() const
  7658. {
  7659. return _begin == _end;
  7660. }
  7661. PUGI__FN const xpath_node& xpath_node_set::operator[](size_t index) const
  7662. {
  7663. assert(index < size());
  7664. return _begin[index];
  7665. }
  7666. PUGI__FN xpath_node_set::const_iterator xpath_node_set::begin() const
  7667. {
  7668. return _begin;
  7669. }
  7670. PUGI__FN xpath_node_set::const_iterator xpath_node_set::end() const
  7671. {
  7672. return _end;
  7673. }
  7674. PUGI__FN void xpath_node_set::sort(bool reverse)
  7675. {
  7676. _type = impl::xpath_sort(_begin, _end, _type, reverse);
  7677. }
  7678. PUGI__FN xpath_node xpath_node_set::first() const
  7679. {
  7680. return impl::xpath_first(_begin, _end, _type);
  7681. }
  7682. PUGI__FN xpath_parse_result::xpath_parse_result(): error("Internal error"), offset(0)
  7683. {
  7684. }
  7685. PUGI__FN xpath_parse_result::operator bool() const
  7686. {
  7687. return error == 0;
  7688. }
  7689. PUGI__FN const char* xpath_parse_result::description() const
  7690. {
  7691. return error ? error : "No error";
  7692. }
  7693. PUGI__FN xpath_variable::xpath_variable()
  7694. {
  7695. }
  7696. PUGI__FN const char_t* xpath_variable::name() const
  7697. {
  7698. switch (_type)
  7699. {
  7700. case xpath_type_node_set:
  7701. return static_cast<const impl::xpath_variable_node_set*>(this)->name;
  7702. case xpath_type_number:
  7703. return static_cast<const impl::xpath_variable_number*>(this)->name;
  7704. case xpath_type_string:
  7705. return static_cast<const impl::xpath_variable_string*>(this)->name;
  7706. case xpath_type_boolean:
  7707. return static_cast<const impl::xpath_variable_boolean*>(this)->name;
  7708. default:
  7709. assert(!"Invalid variable type");
  7710. return 0;
  7711. }
  7712. }
  7713. PUGI__FN xpath_value_type xpath_variable::type() const
  7714. {
  7715. return _type;
  7716. }
  7717. PUGI__FN bool xpath_variable::get_boolean() const
  7718. {
  7719. return (_type == xpath_type_boolean) ? static_cast<const impl::xpath_variable_boolean*>(this)->value : false;
  7720. }
  7721. PUGI__FN double xpath_variable::get_number() const
  7722. {
  7723. return (_type == xpath_type_number) ? static_cast<const impl::xpath_variable_number*>(this)->value : impl::gen_nan();
  7724. }
  7725. PUGI__FN const char_t* xpath_variable::get_string() const
  7726. {
  7727. const char_t* value = (_type == xpath_type_string) ? static_cast<const impl::xpath_variable_string*>(this)->value : 0;
  7728. return value ? value : PUGIXML_TEXT("");
  7729. }
  7730. PUGI__FN const xpath_node_set& xpath_variable::get_node_set() const
  7731. {
  7732. return (_type == xpath_type_node_set) ? static_cast<const impl::xpath_variable_node_set*>(this)->value : impl::dummy_node_set;
  7733. }
  7734. PUGI__FN bool xpath_variable::set(bool value)
  7735. {
  7736. if (_type != xpath_type_boolean) return false;
  7737. static_cast<impl::xpath_variable_boolean*>(this)->value = value;
  7738. return true;
  7739. }
  7740. PUGI__FN bool xpath_variable::set(double value)
  7741. {
  7742. if (_type != xpath_type_number) return false;
  7743. static_cast<impl::xpath_variable_number*>(this)->value = value;
  7744. return true;
  7745. }
  7746. PUGI__FN bool xpath_variable::set(const char_t* value)
  7747. {
  7748. if (_type != xpath_type_string) return false;
  7749. impl::xpath_variable_string* var = static_cast<impl::xpath_variable_string*>(this);
  7750. // duplicate string
  7751. size_t size = (impl::strlength(value) + 1) * sizeof(char_t);
  7752. char_t* copy = static_cast<char_t*>(impl::xml_memory::allocate(size));
  7753. if (!copy) return false;
  7754. memcpy(copy, value, size);
  7755. // replace old string
  7756. if (var->value) impl::xml_memory::deallocate(var->value);
  7757. var->value = copy;
  7758. return true;
  7759. }
  7760. PUGI__FN bool xpath_variable::set(const xpath_node_set& value)
  7761. {
  7762. if (_type != xpath_type_node_set) return false;
  7763. static_cast<impl::xpath_variable_node_set*>(this)->value = value;
  7764. return true;
  7765. }
  7766. PUGI__FN xpath_variable_set::xpath_variable_set()
  7767. {
  7768. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i) _data[i] = 0;
  7769. }
  7770. PUGI__FN xpath_variable_set::~xpath_variable_set()
  7771. {
  7772. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  7773. {
  7774. xpath_variable* var = _data[i];
  7775. while (var)
  7776. {
  7777. xpath_variable* next = var->_next;
  7778. impl::delete_xpath_variable(var->_type, var);
  7779. var = next;
  7780. }
  7781. }
  7782. }
  7783. PUGI__FN xpath_variable* xpath_variable_set::find(const char_t* name) const
  7784. {
  7785. const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
  7786. size_t hash = impl::hash_string(name) % hash_size;
  7787. // look for existing variable
  7788. for (xpath_variable* var = _data[hash]; var; var = var->_next)
  7789. if (impl::strequal(var->name(), name))
  7790. return var;
  7791. return 0;
  7792. }
  7793. PUGI__FN xpath_variable* xpath_variable_set::add(const char_t* name, xpath_value_type type)
  7794. {
  7795. const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
  7796. size_t hash = impl::hash_string(name) % hash_size;
  7797. // look for existing variable
  7798. for (xpath_variable* var = _data[hash]; var; var = var->_next)
  7799. if (impl::strequal(var->name(), name))
  7800. return var->type() == type ? var : 0;
  7801. // add new variable
  7802. xpath_variable* result = impl::new_xpath_variable(type, name);
  7803. if (result)
  7804. {
  7805. result->_type = type;
  7806. result->_next = _data[hash];
  7807. _data[hash] = result;
  7808. }
  7809. return result;
  7810. }
  7811. PUGI__FN bool xpath_variable_set::set(const char_t* name, bool value)
  7812. {
  7813. xpath_variable* var = add(name, xpath_type_boolean);
  7814. return var ? var->set(value) : false;
  7815. }
  7816. PUGI__FN bool xpath_variable_set::set(const char_t* name, double value)
  7817. {
  7818. xpath_variable* var = add(name, xpath_type_number);
  7819. return var ? var->set(value) : false;
  7820. }
  7821. PUGI__FN bool xpath_variable_set::set(const char_t* name, const char_t* value)
  7822. {
  7823. xpath_variable* var = add(name, xpath_type_string);
  7824. return var ? var->set(value) : false;
  7825. }
  7826. PUGI__FN bool xpath_variable_set::set(const char_t* name, const xpath_node_set& value)
  7827. {
  7828. xpath_variable* var = add(name, xpath_type_node_set);
  7829. return var ? var->set(value) : false;
  7830. }
  7831. PUGI__FN xpath_variable* xpath_variable_set::get(const char_t* name)
  7832. {
  7833. return find(name);
  7834. }
  7835. PUGI__FN const xpath_variable* xpath_variable_set::get(const char_t* name) const
  7836. {
  7837. return find(name);
  7838. }
  7839. PUGI__FN xpath_query::xpath_query(const char_t* query, xpath_variable_set* variables): _impl(0)
  7840. {
  7841. impl::xpath_query_impl* qimpl = impl::xpath_query_impl::create();
  7842. if (!qimpl)
  7843. {
  7844. #ifdef PUGIXML_NO_EXCEPTIONS
  7845. _result.error = "Out of memory";
  7846. #else
  7847. throw std::bad_alloc();
  7848. #endif
  7849. }
  7850. else
  7851. {
  7852. impl::buffer_holder impl_holder(qimpl, impl::xpath_query_impl::destroy);
  7853. qimpl->root = impl::xpath_parser::parse(query, variables, &qimpl->alloc, &_result);
  7854. if (qimpl->root)
  7855. {
  7856. _impl = static_cast<impl::xpath_query_impl*>(impl_holder.release());
  7857. _result.error = 0;
  7858. }
  7859. }
  7860. }
  7861. PUGI__FN xpath_query::~xpath_query()
  7862. {
  7863. impl::xpath_query_impl::destroy(_impl);
  7864. }
  7865. PUGI__FN xpath_value_type xpath_query::return_type() const
  7866. {
  7867. if (!_impl) return xpath_type_none;
  7868. return static_cast<impl::xpath_query_impl*>(_impl)->root->rettype();
  7869. }
  7870. PUGI__FN bool xpath_query::evaluate_boolean(const xpath_node& n) const
  7871. {
  7872. if (!_impl) return false;
  7873. impl::xpath_context c(n, 1, 1);
  7874. impl::xpath_stack_data sd;
  7875. #ifdef PUGIXML_NO_EXCEPTIONS
  7876. if (setjmp(sd.error_handler)) return false;
  7877. #endif
  7878. return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_boolean(c, sd.stack);
  7879. }
  7880. PUGI__FN double xpath_query::evaluate_number(const xpath_node& n) const
  7881. {
  7882. if (!_impl) return impl::gen_nan();
  7883. impl::xpath_context c(n, 1, 1);
  7884. impl::xpath_stack_data sd;
  7885. #ifdef PUGIXML_NO_EXCEPTIONS
  7886. if (setjmp(sd.error_handler)) return impl::gen_nan();
  7887. #endif
  7888. return static_cast<impl::xpath_query_impl*>(_impl)->root->eval_number(c, sd.stack);
  7889. }
  7890. #ifndef PUGIXML_NO_STL
  7891. PUGI__FN string_t xpath_query::evaluate_string(const xpath_node& n) const
  7892. {
  7893. impl::xpath_stack_data sd;
  7894. return impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd).c_str();
  7895. }
  7896. #endif
  7897. PUGI__FN size_t xpath_query::evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const
  7898. {
  7899. impl::xpath_stack_data sd;
  7900. impl::xpath_string r = impl::evaluate_string_impl(static_cast<impl::xpath_query_impl*>(_impl), n, sd);
  7901. size_t full_size = r.length() + 1;
  7902. if (capacity > 0)
  7903. {
  7904. size_t size = (full_size < capacity) ? full_size : capacity;
  7905. assert(size > 0);
  7906. memcpy(buffer, r.c_str(), (size - 1) * sizeof(char_t));
  7907. buffer[size - 1] = 0;
  7908. }
  7909. return full_size;
  7910. }
  7911. PUGI__FN xpath_node_set xpath_query::evaluate_node_set(const xpath_node& n) const
  7912. {
  7913. if (!_impl) return xpath_node_set();
  7914. impl::xpath_ast_node* root = static_cast<impl::xpath_query_impl*>(_impl)->root;
  7915. if (root->rettype() != xpath_type_node_set)
  7916. {
  7917. #ifdef PUGIXML_NO_EXCEPTIONS
  7918. return xpath_node_set();
  7919. #else
  7920. xpath_parse_result res;
  7921. res.error = "Expression does not evaluate to node set";
  7922. throw xpath_exception(res);
  7923. #endif
  7924. }
  7925. impl::xpath_context c(n, 1, 1);
  7926. impl::xpath_stack_data sd;
  7927. #ifdef PUGIXML_NO_EXCEPTIONS
  7928. if (setjmp(sd.error_handler)) return xpath_node_set();
  7929. #endif
  7930. impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack);
  7931. return xpath_node_set(r.begin(), r.end(), r.type());
  7932. }
  7933. PUGI__FN const xpath_parse_result& xpath_query::result() const
  7934. {
  7935. return _result;
  7936. }
  7937. PUGI__FN static void unspecified_bool_xpath_query(xpath_query***)
  7938. {
  7939. }
  7940. PUGI__FN xpath_query::operator xpath_query::unspecified_bool_type() const
  7941. {
  7942. return _impl ? unspecified_bool_xpath_query : 0;
  7943. }
  7944. PUGI__FN bool xpath_query::operator!() const
  7945. {
  7946. return !_impl;
  7947. }
  7948. PUGI__FN xpath_node xml_node::select_single_node(const char_t* query, xpath_variable_set* variables) const
  7949. {
  7950. xpath_query q(query, variables);
  7951. return select_single_node(q);
  7952. }
  7953. PUGI__FN xpath_node xml_node::select_single_node(const xpath_query& query) const
  7954. {
  7955. xpath_node_set s = query.evaluate_node_set(*this);
  7956. return s.empty() ? xpath_node() : s.first();
  7957. }
  7958. PUGI__FN xpath_node_set xml_node::select_nodes(const char_t* query, xpath_variable_set* variables) const
  7959. {
  7960. xpath_query q(query, variables);
  7961. return select_nodes(q);
  7962. }
  7963. PUGI__FN xpath_node_set xml_node::select_nodes(const xpath_query& query) const
  7964. {
  7965. return query.evaluate_node_set(*this);
  7966. }
  7967. }
  7968. #endif
  7969. #ifdef __BORLANDC__
  7970. # pragma option pop
  7971. #endif
  7972. // Intel C++ does not properly keep warning state for function templates,
  7973. // so popping warning state at the end of translation unit leads to warnings in the middle.
  7974. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  7975. # pragma warning(pop)
  7976. #endif
  7977. // Undefine all local macros (makes sure we're not leaking macros in header-only mode)
  7978. #undef PUGI__NO_INLINE
  7979. #undef PUGI__STATIC_ASSERT
  7980. #undef PUGI__DMC_VOLATILE
  7981. #undef PUGI__MSVC_CRT_VERSION
  7982. #undef PUGI__NS_BEGIN
  7983. #undef PUGI__NS_END
  7984. #undef PUGI__FN
  7985. #undef PUGI__FN_NO_INLINE
  7986. #undef PUGI__IS_CHARTYPE_IMPL
  7987. #undef PUGI__IS_CHARTYPE
  7988. #undef PUGI__IS_CHARTYPEX
  7989. #undef PUGI__SKIPWS
  7990. #undef PUGI__OPTSET
  7991. #undef PUGI__PUSHNODE
  7992. #undef PUGI__POPNODE
  7993. #undef PUGI__SCANFOR
  7994. #undef PUGI__SCANWHILE
  7995. #undef PUGI__ENDSEG
  7996. #undef PUGI__THROW_ERROR
  7997. #undef PUGI__CHECK_ERROR
  7998. #endif
  7999. /**
  8000. * Copyright (c) 2006-2012 Arseny Kapoulkine
  8001. *
  8002. * Permission is hereby granted, free of charge, to any person
  8003. * obtaining a copy of this software and associated documentation
  8004. * files (the "Software"), to deal in the Software without
  8005. * restriction, including without limitation the rights to use,
  8006. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  8007. * copies of the Software, and to permit persons to whom the
  8008. * Software is furnished to do so, subject to the following
  8009. * conditions:
  8010. *
  8011. * The above copyright notice and this permission notice shall be
  8012. * included in all copies or substantial portions of the Software.
  8013. *
  8014. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  8015. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  8016. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  8017. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  8018. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  8019. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  8020. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  8021. * OTHER DEALINGS IN THE SOFTWARE.
  8022. */