pugixml.cpp 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866
  1. #include "stdafx.h"
  2. /**
  3. * pugixml parser - version 1.10
  4. * --------------------------------------------------------
  5. * Copyright (C) 2006-2019, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  6. * Report bugs and download new versions at https://pugixml.org/
  7. *
  8. * This library is distributed under the MIT License. See notice at the end
  9. * of this file.
  10. *
  11. * This work is based on the pugxml parser, which is:
  12. * Copyright (C) 2003, by Kristen Wegner (kristen@tima.net)
  13. */
  14. #ifndef SOURCE_PUGIXML_CPP
  15. #define SOURCE_PUGIXML_CPP
  16. #include "pugixml.hpp"
  17. #include <stdlib.h>
  18. #include <stdio.h>
  19. #include <string.h>
  20. #include <assert.h>
  21. #include <limits.h>
  22. #ifdef PUGIXML_WCHAR_MODE
  23. # include <wchar.h>
  24. #endif
  25. #ifndef PUGIXML_NO_XPATH
  26. # include <math.h>
  27. # include <float.h>
  28. #endif
  29. #ifndef PUGIXML_NO_STL
  30. # include <istream>
  31. # include <ostream>
  32. # include <string>
  33. #endif
  34. // For placement new
  35. #include <new>
  36. #ifdef _MSC_VER
  37. # pragma warning(push)
  38. # pragma warning(disable: 4127) // conditional expression is constant
  39. # pragma warning(disable: 4324) // structure was padded due to __declspec(align())
  40. # pragma warning(disable: 4702) // unreachable code
  41. # pragma warning(disable: 4996) // this function or variable may be unsafe
  42. #endif
  43. #if defined(_MSC_VER) && defined(__c2__)
  44. # pragma clang diagnostic push
  45. # pragma clang diagnostic ignored "-Wdeprecated" // this function or variable may be unsafe
  46. #endif
  47. #ifdef __INTEL_COMPILER
  48. # pragma warning(disable: 177) // function was declared but never referenced
  49. # pragma warning(disable: 279) // controlling expression is constant
  50. # pragma warning(disable: 1478 1786) // function was declared "deprecated"
  51. # pragma warning(disable: 1684) // conversion from pointer to same-sized integral type
  52. #endif
  53. #if defined(__BORLANDC__) && defined(PUGIXML_HEADER_ONLY)
  54. # pragma warn -8080 // symbol is declared but never used; disabling this inside push/pop bracket does not make the warning go away
  55. #endif
  56. #ifdef __BORLANDC__
  57. # pragma option push
  58. # pragma warn -8008 // condition is always false
  59. # pragma warn -8066 // unreachable code
  60. #endif
  61. #ifdef __SNC__
  62. // Using diag_push/diag_pop does not disable the warnings inside templates due to a compiler bug
  63. # pragma diag_suppress=178 // function was declared but never referenced
  64. # pragma diag_suppress=237 // controlling expression is constant
  65. #endif
  66. #ifdef __TI_COMPILER_VERSION__
  67. # pragma diag_suppress 179 // function was declared but never referenced
  68. #endif
  69. // Inlining controls
  70. #if defined(_MSC_VER) && _MSC_VER >= 1300
  71. # define PUGI__NO_INLINE __declspec(noinline)
  72. #elif defined(__GNUC__)
  73. # define PUGI__NO_INLINE __attribute__((noinline))
  74. #else
  75. # define PUGI__NO_INLINE
  76. #endif
  77. // Branch weight controls
  78. #if defined(__GNUC__) && !defined(__c2__)
  79. # define PUGI__UNLIKELY(cond) __builtin_expect(cond, 0)
  80. #else
  81. # define PUGI__UNLIKELY(cond) (cond)
  82. #endif
  83. // Simple static assertion
  84. #define PUGI__STATIC_ASSERT(cond) { static const char condition_failed[(cond) ? 1 : -1] = {0}; (void)condition_failed[0]; }
  85. // Digital Mars C++ bug workaround for passing char loaded from memory via stack
  86. #ifdef __DMC__
  87. # define PUGI__DMC_VOLATILE volatile
  88. #else
  89. # define PUGI__DMC_VOLATILE
  90. #endif
  91. // Integer sanitizer workaround; we only apply this for clang since gcc8 has no_sanitize but not unsigned-integer-overflow and produces "attribute directive ignored" warnings
  92. #if defined(__clang__) && defined(__has_attribute)
  93. # if __has_attribute(no_sanitize)
  94. # define PUGI__UNSIGNED_OVERFLOW __attribute__((no_sanitize("unsigned-integer-overflow")))
  95. # else
  96. # define PUGI__UNSIGNED_OVERFLOW
  97. # endif
  98. #else
  99. # define PUGI__UNSIGNED_OVERFLOW
  100. #endif
  101. // 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)
  102. #if defined(__BORLANDC__) && !defined(__MEM_H_USING_LIST)
  103. using std::memcpy;
  104. using std::memmove;
  105. using std::memset;
  106. #endif
  107. // Some MinGW/GCC versions have headers that erroneously omit LLONG_MIN/LLONG_MAX/ULLONG_MAX definitions from limits.h in some configurations
  108. #if defined(PUGIXML_HAS_LONG_LONG) && defined(__GNUC__) && !defined(LLONG_MAX) && !defined(LLONG_MIN) && !defined(ULLONG_MAX)
  109. # define LLONG_MIN (-LLONG_MAX - 1LL)
  110. # define LLONG_MAX __LONG_LONG_MAX__
  111. # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
  112. #endif
  113. // In some environments MSVC is a compiler but the CRT lacks certain MSVC-specific features
  114. #if defined(_MSC_VER) && !defined(__S3E__)
  115. # define PUGI__MSVC_CRT_VERSION _MSC_VER
  116. #endif
  117. // Not all platforms have snprintf; we define a wrapper that uses snprintf if possible. This only works with buffers with a known size.
  118. #if __cplusplus >= 201103
  119. # define PUGI__SNPRINTF(buf, ...) snprintf(buf, sizeof(buf), __VA_ARGS__)
  120. #elif defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400
  121. # define PUGI__SNPRINTF(buf, ...) _snprintf_s(buf, _countof(buf), _TRUNCATE, __VA_ARGS__)
  122. #else
  123. # define PUGI__SNPRINTF sprintf
  124. #endif
  125. // We put implementation details into an anonymous namespace in source mode, but have to keep it in non-anonymous namespace in header-only mode to prevent binary bloat.
  126. #ifdef PUGIXML_HEADER_ONLY
  127. # define PUGI__NS_BEGIN namespace pugi { namespace impl {
  128. # define PUGI__NS_END } }
  129. # define PUGI__FN inline
  130. # define PUGI__FN_NO_INLINE inline
  131. #else
  132. # if defined(_MSC_VER) && _MSC_VER < 1300 // MSVC6 seems to have an amusing bug with anonymous namespaces inside namespaces
  133. # define PUGI__NS_BEGIN namespace pugi { namespace impl {
  134. # define PUGI__NS_END } }
  135. # else
  136. # define PUGI__NS_BEGIN namespace pugi { namespace impl { namespace {
  137. # define PUGI__NS_END } } }
  138. # endif
  139. # define PUGI__FN
  140. # define PUGI__FN_NO_INLINE PUGI__NO_INLINE
  141. #endif
  142. // uintptr_t
  143. #if (defined(_MSC_VER) && _MSC_VER < 1600) || (defined(__BORLANDC__) && __BORLANDC__ < 0x561)
  144. namespace pugi
  145. {
  146. # ifndef _UINTPTR_T_DEFINED
  147. typedef size_t uintptr_t;
  148. # endif
  149. typedef unsigned __int8 uint8_t;
  150. typedef unsigned __int16 uint16_t;
  151. typedef unsigned __int32 uint32_t;
  152. }
  153. #else
  154. # include <stdint.h>
  155. #endif
  156. // Memory allocation
  157. PUGI__NS_BEGIN
  158. PUGI__FN void* default_allocate(size_t size)
  159. {
  160. return malloc(size);
  161. }
  162. PUGI__FN void default_deallocate(void* ptr)
  163. {
  164. free(ptr);
  165. }
  166. template <typename T>
  167. struct xml_memory_management_function_storage
  168. {
  169. static allocation_function allocate;
  170. static deallocation_function deallocate;
  171. };
  172. // Global allocation functions are stored in class statics so that in header mode linker deduplicates them
  173. // Without a template<> we'll get multiple definitions of the same static
  174. template <typename T> allocation_function xml_memory_management_function_storage<T>::allocate = default_allocate;
  175. template <typename T> deallocation_function xml_memory_management_function_storage<T>::deallocate = default_deallocate;
  176. typedef xml_memory_management_function_storage<int> xml_memory;
  177. PUGI__NS_END
  178. // String utilities
  179. PUGI__NS_BEGIN
  180. // Get string length
  181. PUGI__FN size_t strlength(const char_t* s)
  182. {
  183. assert(s);
  184. #ifdef PUGIXML_WCHAR_MODE
  185. return wcslen(s);
  186. #else
  187. return strlen(s);
  188. #endif
  189. }
  190. // Compare two strings
  191. PUGI__FN bool strequal(const char_t* src, const char_t* dst)
  192. {
  193. assert(src && dst);
  194. #ifdef PUGIXML_WCHAR_MODE
  195. return wcscmp(src, dst) == 0;
  196. #else
  197. return strcmp(src, dst) == 0;
  198. #endif
  199. }
  200. // Compare lhs with [rhs_begin, rhs_end)
  201. PUGI__FN bool strequalrange(const char_t* lhs, const char_t* rhs, size_t count)
  202. {
  203. for (size_t i = 0; i < count; ++i)
  204. if (lhs[i] != rhs[i])
  205. return false;
  206. return lhs[count] == 0;
  207. }
  208. // Get length of wide string, even if CRT lacks wide character support
  209. PUGI__FN size_t strlength_wide(const wchar_t* s)
  210. {
  211. assert(s);
  212. #ifdef PUGIXML_WCHAR_MODE
  213. return wcslen(s);
  214. #else
  215. const wchar_t* end = s;
  216. while (*end) end++;
  217. return static_cast<size_t>(end - s);
  218. #endif
  219. }
  220. PUGI__NS_END
  221. // auto_ptr-like object for exception recovery
  222. PUGI__NS_BEGIN
  223. template <typename T> struct auto_deleter
  224. {
  225. typedef void (*D)(T*);
  226. T* data;
  227. D deleter;
  228. auto_deleter(T* data_, D deleter_): data(data_), deleter(deleter_)
  229. {
  230. }
  231. ~auto_deleter()
  232. {
  233. if (data) deleter(data);
  234. }
  235. T* release()
  236. {
  237. T* result = data;
  238. data = 0;
  239. return result;
  240. }
  241. };
  242. PUGI__NS_END
  243. #ifdef PUGIXML_COMPACT
  244. PUGI__NS_BEGIN
  245. class compact_hash_table
  246. {
  247. public:
  248. compact_hash_table(): _items(0), _capacity(0), _count(0)
  249. {
  250. }
  251. void clear()
  252. {
  253. if (_items)
  254. {
  255. xml_memory::deallocate(_items);
  256. _items = 0;
  257. _capacity = 0;
  258. _count = 0;
  259. }
  260. }
  261. void* find(const void* key)
  262. {
  263. if (_capacity == 0) return 0;
  264. item_t* item = get_item(key);
  265. assert(item);
  266. assert(item->key == key || (item->key == 0 && item->value == 0));
  267. return item->value;
  268. }
  269. void insert(const void* key, void* value)
  270. {
  271. assert(_capacity != 0 && _count < _capacity - _capacity / 4);
  272. item_t* item = get_item(key);
  273. assert(item);
  274. if (item->key == 0)
  275. {
  276. _count++;
  277. item->key = key;
  278. }
  279. item->value = value;
  280. }
  281. bool reserve(size_t extra = 16)
  282. {
  283. if (_count + extra >= _capacity - _capacity / 4)
  284. return rehash(_count + extra);
  285. return true;
  286. }
  287. private:
  288. struct item_t
  289. {
  290. const void* key;
  291. void* value;
  292. };
  293. item_t* _items;
  294. size_t _capacity;
  295. size_t _count;
  296. bool rehash(size_t count);
  297. item_t* get_item(const void* key)
  298. {
  299. assert(key);
  300. assert(_capacity > 0);
  301. size_t hashmod = _capacity - 1;
  302. size_t bucket = hash(key) & hashmod;
  303. for (size_t probe = 0; probe <= hashmod; ++probe)
  304. {
  305. item_t& probe_item = _items[bucket];
  306. if (probe_item.key == key || probe_item.key == 0)
  307. return &probe_item;
  308. // hash collision, quadratic probing
  309. bucket = (bucket + probe + 1) & hashmod;
  310. }
  311. assert(false && "Hash table is full"); // unreachable
  312. return 0;
  313. }
  314. static PUGI__UNSIGNED_OVERFLOW unsigned int hash(const void* key)
  315. {
  316. unsigned int h = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(key));
  317. // MurmurHash3 32-bit finalizer
  318. h ^= h >> 16;
  319. h *= 0x85ebca6bu;
  320. h ^= h >> 13;
  321. h *= 0xc2b2ae35u;
  322. h ^= h >> 16;
  323. return h;
  324. }
  325. };
  326. PUGI__FN_NO_INLINE bool compact_hash_table::rehash(size_t count)
  327. {
  328. size_t capacity = 32;
  329. while (count >= capacity - capacity / 4)
  330. capacity *= 2;
  331. compact_hash_table rt;
  332. rt._capacity = capacity;
  333. rt._items = static_cast<item_t*>(xml_memory::allocate(sizeof(item_t) * capacity));
  334. if (!rt._items)
  335. return false;
  336. memset(rt._items, 0, sizeof(item_t) * capacity);
  337. for (size_t i = 0; i < _capacity; ++i)
  338. if (_items[i].key)
  339. rt.insert(_items[i].key, _items[i].value);
  340. if (_items)
  341. xml_memory::deallocate(_items);
  342. _capacity = capacity;
  343. _items = rt._items;
  344. assert(_count == rt._count);
  345. return true;
  346. }
  347. PUGI__NS_END
  348. #endif
  349. PUGI__NS_BEGIN
  350. #ifdef PUGIXML_COMPACT
  351. static const uintptr_t xml_memory_block_alignment = 4;
  352. #else
  353. static const uintptr_t xml_memory_block_alignment = sizeof(void*);
  354. #endif
  355. // extra metadata bits
  356. static const uintptr_t xml_memory_page_contents_shared_mask = 64;
  357. static const uintptr_t xml_memory_page_name_allocated_mask = 32;
  358. static const uintptr_t xml_memory_page_value_allocated_mask = 16;
  359. static const uintptr_t xml_memory_page_type_mask = 15;
  360. // combined masks for string uniqueness
  361. static const uintptr_t xml_memory_page_name_allocated_or_shared_mask = xml_memory_page_name_allocated_mask | xml_memory_page_contents_shared_mask;
  362. static const uintptr_t xml_memory_page_value_allocated_or_shared_mask = xml_memory_page_value_allocated_mask | xml_memory_page_contents_shared_mask;
  363. #ifdef PUGIXML_COMPACT
  364. #define PUGI__GETHEADER_IMPL(object, page, flags) // unused
  365. #define PUGI__GETPAGE_IMPL(header) (header).get_page()
  366. #else
  367. #define PUGI__GETHEADER_IMPL(object, page, flags) (((reinterpret_cast<char*>(object) - reinterpret_cast<char*>(page)) << 8) | (flags))
  368. // this macro casts pointers through void* to avoid 'cast increases required alignment of target type' warnings
  369. #define PUGI__GETPAGE_IMPL(header) static_cast<impl::xml_memory_page*>(const_cast<void*>(static_cast<const void*>(reinterpret_cast<const char*>(&header) - (header >> 8))))
  370. #endif
  371. #define PUGI__GETPAGE(n) PUGI__GETPAGE_IMPL((n)->header)
  372. #define PUGI__NODETYPE(n) static_cast<xml_node_type>((n)->header & impl::xml_memory_page_type_mask)
  373. struct xml_allocator;
  374. struct xml_memory_page
  375. {
  376. static xml_memory_page* construct(void* memory)
  377. {
  378. xml_memory_page* result = static_cast<xml_memory_page*>(memory);
  379. result->allocator = 0;
  380. result->prev = 0;
  381. result->next = 0;
  382. result->busy_size = 0;
  383. result->freed_size = 0;
  384. #ifdef PUGIXML_COMPACT
  385. result->compact_string_base = 0;
  386. result->compact_shared_parent = 0;
  387. result->compact_page_marker = 0;
  388. #endif
  389. return result;
  390. }
  391. xml_allocator* allocator;
  392. xml_memory_page* prev;
  393. xml_memory_page* next;
  394. size_t busy_size;
  395. size_t freed_size;
  396. #ifdef PUGIXML_COMPACT
  397. char_t* compact_string_base;
  398. void* compact_shared_parent;
  399. uint32_t* compact_page_marker;
  400. #endif
  401. };
  402. static const size_t xml_memory_page_size =
  403. #ifdef PUGIXML_MEMORY_PAGE_SIZE
  404. (PUGIXML_MEMORY_PAGE_SIZE)
  405. #else
  406. 32768
  407. #endif
  408. - sizeof(xml_memory_page);
  409. struct xml_memory_string_header
  410. {
  411. uint16_t page_offset; // offset from page->data
  412. uint16_t full_size; // 0 if string occupies whole page
  413. };
  414. struct xml_allocator
  415. {
  416. xml_allocator(xml_memory_page* root): _root(root), _busy_size(root->busy_size)
  417. {
  418. #ifdef PUGIXML_COMPACT
  419. _hash = 0;
  420. #endif
  421. }
  422. xml_memory_page* allocate_page(size_t data_size)
  423. {
  424. size_t size = sizeof(xml_memory_page) + data_size;
  425. // allocate block with some alignment, leaving memory for worst-case padding
  426. void* memory = xml_memory::allocate(size);
  427. if (!memory) return 0;
  428. // prepare page structure
  429. xml_memory_page* page = xml_memory_page::construct(memory);
  430. assert(page);
  431. page->allocator = _root->allocator;
  432. return page;
  433. }
  434. static void deallocate_page(xml_memory_page* page)
  435. {
  436. xml_memory::deallocate(page);
  437. }
  438. void* allocate_memory_oob(size_t size, xml_memory_page*& out_page);
  439. void* allocate_memory(size_t size, xml_memory_page*& out_page)
  440. {
  441. if (PUGI__UNLIKELY(_busy_size + size > xml_memory_page_size))
  442. return allocate_memory_oob(size, out_page);
  443. void* buf = reinterpret_cast<char*>(_root) + sizeof(xml_memory_page) + _busy_size;
  444. _busy_size += size;
  445. out_page = _root;
  446. return buf;
  447. }
  448. #ifdef PUGIXML_COMPACT
  449. void* allocate_object(size_t size, xml_memory_page*& out_page)
  450. {
  451. void* result = allocate_memory(size + sizeof(uint32_t), out_page);
  452. if (!result) return 0;
  453. // adjust for marker
  454. ptrdiff_t offset = static_cast<char*>(result) - reinterpret_cast<char*>(out_page->compact_page_marker);
  455. if (PUGI__UNLIKELY(static_cast<uintptr_t>(offset) >= 256 * xml_memory_block_alignment))
  456. {
  457. // insert new marker
  458. uint32_t* marker = static_cast<uint32_t*>(result);
  459. *marker = static_cast<uint32_t>(reinterpret_cast<char*>(marker) - reinterpret_cast<char*>(out_page));
  460. out_page->compact_page_marker = marker;
  461. // since we don't reuse the page space until we reallocate it, we can just pretend that we freed the marker block
  462. // this will make sure deallocate_memory correctly tracks the size
  463. out_page->freed_size += sizeof(uint32_t);
  464. return marker + 1;
  465. }
  466. else
  467. {
  468. // roll back uint32_t part
  469. _busy_size -= sizeof(uint32_t);
  470. return result;
  471. }
  472. }
  473. #else
  474. void* allocate_object(size_t size, xml_memory_page*& out_page)
  475. {
  476. return allocate_memory(size, out_page);
  477. }
  478. #endif
  479. void deallocate_memory(void* ptr, size_t size, xml_memory_page* page)
  480. {
  481. if (page == _root) page->busy_size = _busy_size;
  482. assert(ptr >= reinterpret_cast<char*>(page) + sizeof(xml_memory_page) && ptr < reinterpret_cast<char*>(page) + sizeof(xml_memory_page) + page->busy_size);
  483. (void)!ptr;
  484. page->freed_size += size;
  485. assert(page->freed_size <= page->busy_size);
  486. if (page->freed_size == page->busy_size)
  487. {
  488. if (page->next == 0)
  489. {
  490. assert(_root == page);
  491. // top page freed, just reset sizes
  492. page->busy_size = 0;
  493. page->freed_size = 0;
  494. #ifdef PUGIXML_COMPACT
  495. // reset compact state to maximize efficiency
  496. page->compact_string_base = 0;
  497. page->compact_shared_parent = 0;
  498. page->compact_page_marker = 0;
  499. #endif
  500. _busy_size = 0;
  501. }
  502. else
  503. {
  504. assert(_root != page);
  505. assert(page->prev);
  506. // remove from the list
  507. page->prev->next = page->next;
  508. page->next->prev = page->prev;
  509. // deallocate
  510. deallocate_page(page);
  511. }
  512. }
  513. }
  514. char_t* allocate_string(size_t length)
  515. {
  516. static const size_t max_encoded_offset = (1 << 16) * xml_memory_block_alignment;
  517. PUGI__STATIC_ASSERT(xml_memory_page_size <= max_encoded_offset);
  518. // allocate memory for string and header block
  519. size_t size = sizeof(xml_memory_string_header) + length * sizeof(char_t);
  520. // round size up to block alignment boundary
  521. size_t full_size = (size + (xml_memory_block_alignment - 1)) & ~(xml_memory_block_alignment - 1);
  522. xml_memory_page* page;
  523. xml_memory_string_header* header = static_cast<xml_memory_string_header*>(allocate_memory(full_size, page));
  524. if (!header) return 0;
  525. // setup header
  526. ptrdiff_t page_offset = reinterpret_cast<char*>(header) - reinterpret_cast<char*>(page) - sizeof(xml_memory_page);
  527. assert(page_offset % xml_memory_block_alignment == 0);
  528. assert(page_offset >= 0 && static_cast<size_t>(page_offset) < max_encoded_offset);
  529. header->page_offset = static_cast<uint16_t>(static_cast<size_t>(page_offset) / xml_memory_block_alignment);
  530. // full_size == 0 for large strings that occupy the whole page
  531. assert(full_size % xml_memory_block_alignment == 0);
  532. assert(full_size < max_encoded_offset || (page->busy_size == full_size && page_offset == 0));
  533. header->full_size = static_cast<uint16_t>(full_size < max_encoded_offset ? full_size / xml_memory_block_alignment : 0);
  534. // round-trip through void* to avoid 'cast increases required alignment of target type' warning
  535. // header is guaranteed a pointer-sized alignment, which should be enough for char_t
  536. return static_cast<char_t*>(static_cast<void*>(header + 1));
  537. }
  538. void deallocate_string(char_t* string)
  539. {
  540. // this function casts pointers through void* to avoid 'cast increases required alignment of target type' warnings
  541. // we're guaranteed the proper (pointer-sized) alignment on the input string if it was allocated via allocate_string
  542. // get header
  543. xml_memory_string_header* header = static_cast<xml_memory_string_header*>(static_cast<void*>(string)) - 1;
  544. assert(header);
  545. // deallocate
  546. size_t page_offset = sizeof(xml_memory_page) + header->page_offset * xml_memory_block_alignment;
  547. xml_memory_page* page = reinterpret_cast<xml_memory_page*>(static_cast<void*>(reinterpret_cast<char*>(header) - page_offset));
  548. // if full_size == 0 then this string occupies the whole page
  549. size_t full_size = header->full_size == 0 ? page->busy_size : header->full_size * xml_memory_block_alignment;
  550. deallocate_memory(header, full_size, page);
  551. }
  552. bool reserve()
  553. {
  554. #ifdef PUGIXML_COMPACT
  555. return _hash->reserve();
  556. #else
  557. return true;
  558. #endif
  559. }
  560. xml_memory_page* _root;
  561. size_t _busy_size;
  562. #ifdef PUGIXML_COMPACT
  563. compact_hash_table* _hash;
  564. #endif
  565. };
  566. PUGI__FN_NO_INLINE void* xml_allocator::allocate_memory_oob(size_t size, xml_memory_page*& out_page)
  567. {
  568. const size_t large_allocation_threshold = xml_memory_page_size / 4;
  569. xml_memory_page* page = allocate_page(size <= large_allocation_threshold ? xml_memory_page_size : size);
  570. out_page = page;
  571. if (!page) return 0;
  572. if (size <= large_allocation_threshold)
  573. {
  574. _root->busy_size = _busy_size;
  575. // insert page at the end of linked list
  576. page->prev = _root;
  577. _root->next = page;
  578. _root = page;
  579. _busy_size = size;
  580. }
  581. else
  582. {
  583. // insert page before the end of linked list, so that it is deleted as soon as possible
  584. // the last page is not deleted even if it's empty (see deallocate_memory)
  585. assert(_root->prev);
  586. page->prev = _root->prev;
  587. page->next = _root;
  588. _root->prev->next = page;
  589. _root->prev = page;
  590. page->busy_size = size;
  591. }
  592. return reinterpret_cast<char*>(page) + sizeof(xml_memory_page);
  593. }
  594. PUGI__NS_END
  595. #ifdef PUGIXML_COMPACT
  596. PUGI__NS_BEGIN
  597. static const uintptr_t compact_alignment_log2 = 2;
  598. static const uintptr_t compact_alignment = 1 << compact_alignment_log2;
  599. class compact_header
  600. {
  601. public:
  602. compact_header(xml_memory_page* page, unsigned int flags)
  603. {
  604. PUGI__STATIC_ASSERT(xml_memory_block_alignment == compact_alignment);
  605. ptrdiff_t offset = (reinterpret_cast<char*>(this) - reinterpret_cast<char*>(page->compact_page_marker));
  606. assert(offset % compact_alignment == 0 && static_cast<uintptr_t>(offset) < 256 * compact_alignment);
  607. _page = static_cast<unsigned char>(offset >> compact_alignment_log2);
  608. _flags = static_cast<unsigned char>(flags);
  609. }
  610. void operator&=(uintptr_t mod)
  611. {
  612. _flags &= static_cast<unsigned char>(mod);
  613. }
  614. void operator|=(uintptr_t mod)
  615. {
  616. _flags |= static_cast<unsigned char>(mod);
  617. }
  618. uintptr_t operator&(uintptr_t mod) const
  619. {
  620. return _flags & mod;
  621. }
  622. xml_memory_page* get_page() const
  623. {
  624. // round-trip through void* to silence 'cast increases required alignment of target type' warnings
  625. const char* page_marker = reinterpret_cast<const char*>(this) - (_page << compact_alignment_log2);
  626. const char* page = page_marker - *reinterpret_cast<const uint32_t*>(static_cast<const void*>(page_marker));
  627. return const_cast<xml_memory_page*>(reinterpret_cast<const xml_memory_page*>(static_cast<const void*>(page)));
  628. }
  629. private:
  630. unsigned char _page;
  631. unsigned char _flags;
  632. };
  633. PUGI__FN xml_memory_page* compact_get_page(const void* object, int header_offset)
  634. {
  635. const compact_header* header = reinterpret_cast<const compact_header*>(static_cast<const char*>(object) - header_offset);
  636. return header->get_page();
  637. }
  638. template <int header_offset, typename T> PUGI__FN_NO_INLINE T* compact_get_value(const void* object)
  639. {
  640. return static_cast<T*>(compact_get_page(object, header_offset)->allocator->_hash->find(object));
  641. }
  642. template <int header_offset, typename T> PUGI__FN_NO_INLINE void compact_set_value(const void* object, T* value)
  643. {
  644. compact_get_page(object, header_offset)->allocator->_hash->insert(object, value);
  645. }
  646. template <typename T, int header_offset, int start = -126> class compact_pointer
  647. {
  648. public:
  649. compact_pointer(): _data(0)
  650. {
  651. }
  652. void operator=(const compact_pointer& rhs)
  653. {
  654. *this = rhs + 0;
  655. }
  656. void operator=(T* value)
  657. {
  658. if (value)
  659. {
  660. // value is guaranteed to be compact-aligned; 'this' is not
  661. // our decoding is based on 'this' aligned to compact alignment downwards (see operator T*)
  662. // so for negative offsets (e.g. -3) we need to adjust the diff by compact_alignment - 1 to
  663. // compensate for arithmetic shift rounding for negative values
  664. ptrdiff_t diff = reinterpret_cast<char*>(value) - reinterpret_cast<char*>(this);
  665. ptrdiff_t offset = ((diff + int(compact_alignment - 1)) >> compact_alignment_log2) - start;
  666. if (static_cast<uintptr_t>(offset) <= 253)
  667. _data = static_cast<unsigned char>(offset + 1);
  668. else
  669. {
  670. compact_set_value<header_offset>(this, value);
  671. _data = 255;
  672. }
  673. }
  674. else
  675. _data = 0;
  676. }
  677. operator T*() const
  678. {
  679. if (_data)
  680. {
  681. if (_data < 255)
  682. {
  683. uintptr_t base = reinterpret_cast<uintptr_t>(this) & ~(compact_alignment - 1);
  684. return reinterpret_cast<T*>(base + (_data - 1 + start) * compact_alignment);
  685. }
  686. else
  687. return compact_get_value<header_offset, T>(this);
  688. }
  689. else
  690. return 0;
  691. }
  692. T* operator->() const
  693. {
  694. return *this;
  695. }
  696. private:
  697. unsigned char _data;
  698. };
  699. template <typename T, int header_offset> class compact_pointer_parent
  700. {
  701. public:
  702. compact_pointer_parent(): _data(0)
  703. {
  704. }
  705. void operator=(const compact_pointer_parent& rhs)
  706. {
  707. *this = rhs + 0;
  708. }
  709. void operator=(T* value)
  710. {
  711. if (value)
  712. {
  713. // value is guaranteed to be compact-aligned; 'this' is not
  714. // our decoding is based on 'this' aligned to compact alignment downwards (see operator T*)
  715. // so for negative offsets (e.g. -3) we need to adjust the diff by compact_alignment - 1 to
  716. // compensate for arithmetic shift behavior for negative values
  717. ptrdiff_t diff = reinterpret_cast<char*>(value) - reinterpret_cast<char*>(this);
  718. ptrdiff_t offset = ((diff + int(compact_alignment - 1)) >> compact_alignment_log2) + 65533;
  719. if (static_cast<uintptr_t>(offset) <= 65533)
  720. {
  721. _data = static_cast<unsigned short>(offset + 1);
  722. }
  723. else
  724. {
  725. xml_memory_page* page = compact_get_page(this, header_offset);
  726. if (PUGI__UNLIKELY(page->compact_shared_parent == 0))
  727. page->compact_shared_parent = value;
  728. if (page->compact_shared_parent == value)
  729. {
  730. _data = 65534;
  731. }
  732. else
  733. {
  734. compact_set_value<header_offset>(this, value);
  735. _data = 65535;
  736. }
  737. }
  738. }
  739. else
  740. {
  741. _data = 0;
  742. }
  743. }
  744. operator T*() const
  745. {
  746. if (_data)
  747. {
  748. if (_data < 65534)
  749. {
  750. uintptr_t base = reinterpret_cast<uintptr_t>(this) & ~(compact_alignment - 1);
  751. return reinterpret_cast<T*>(base + (_data - 1 - 65533) * compact_alignment);
  752. }
  753. else if (_data == 65534)
  754. return static_cast<T*>(compact_get_page(this, header_offset)->compact_shared_parent);
  755. else
  756. return compact_get_value<header_offset, T>(this);
  757. }
  758. else
  759. return 0;
  760. }
  761. T* operator->() const
  762. {
  763. return *this;
  764. }
  765. private:
  766. uint16_t _data;
  767. };
  768. template <int header_offset, int base_offset> class compact_string
  769. {
  770. public:
  771. compact_string(): _data(0)
  772. {
  773. }
  774. void operator=(const compact_string& rhs)
  775. {
  776. *this = rhs + 0;
  777. }
  778. void operator=(char_t* value)
  779. {
  780. if (value)
  781. {
  782. xml_memory_page* page = compact_get_page(this, header_offset);
  783. if (PUGI__UNLIKELY(page->compact_string_base == 0))
  784. page->compact_string_base = value;
  785. ptrdiff_t offset = value - page->compact_string_base;
  786. if (static_cast<uintptr_t>(offset) < (65535 << 7))
  787. {
  788. // round-trip through void* to silence 'cast increases required alignment of target type' warnings
  789. uint16_t* base = reinterpret_cast<uint16_t*>(static_cast<void*>(reinterpret_cast<char*>(this) - base_offset));
  790. if (*base == 0)
  791. {
  792. *base = static_cast<uint16_t>((offset >> 7) + 1);
  793. _data = static_cast<unsigned char>((offset & 127) + 1);
  794. }
  795. else
  796. {
  797. ptrdiff_t remainder = offset - ((*base - 1) << 7);
  798. if (static_cast<uintptr_t>(remainder) <= 253)
  799. {
  800. _data = static_cast<unsigned char>(remainder + 1);
  801. }
  802. else
  803. {
  804. compact_set_value<header_offset>(this, value);
  805. _data = 255;
  806. }
  807. }
  808. }
  809. else
  810. {
  811. compact_set_value<header_offset>(this, value);
  812. _data = 255;
  813. }
  814. }
  815. else
  816. {
  817. _data = 0;
  818. }
  819. }
  820. operator char_t*() const
  821. {
  822. if (_data)
  823. {
  824. if (_data < 255)
  825. {
  826. xml_memory_page* page = compact_get_page(this, header_offset);
  827. // round-trip through void* to silence 'cast increases required alignment of target type' warnings
  828. const uint16_t* base = reinterpret_cast<const uint16_t*>(static_cast<const void*>(reinterpret_cast<const char*>(this) - base_offset));
  829. assert(*base);
  830. ptrdiff_t offset = ((*base - 1) << 7) + (_data - 1);
  831. return page->compact_string_base + offset;
  832. }
  833. else
  834. {
  835. return compact_get_value<header_offset, char_t>(this);
  836. }
  837. }
  838. else
  839. return 0;
  840. }
  841. private:
  842. unsigned char _data;
  843. };
  844. PUGI__NS_END
  845. #endif
  846. #ifdef PUGIXML_COMPACT
  847. namespace pugi
  848. {
  849. struct xml_attribute_struct
  850. {
  851. xml_attribute_struct(impl::xml_memory_page* page): header(page, 0), namevalue_base(0)
  852. {
  853. PUGI__STATIC_ASSERT(sizeof(xml_attribute_struct) == 8);
  854. }
  855. impl::compact_header header;
  856. uint16_t namevalue_base;
  857. impl::compact_string<4, 2> name;
  858. impl::compact_string<5, 3> value;
  859. impl::compact_pointer<xml_attribute_struct, 6> prev_attribute_c;
  860. impl::compact_pointer<xml_attribute_struct, 7, 0> next_attribute;
  861. };
  862. struct xml_node_struct
  863. {
  864. xml_node_struct(impl::xml_memory_page* page, xml_node_type type): header(page, type), namevalue_base(0)
  865. {
  866. PUGI__STATIC_ASSERT(sizeof(xml_node_struct) == 12);
  867. }
  868. impl::compact_header header;
  869. uint16_t namevalue_base;
  870. impl::compact_string<4, 2> name;
  871. impl::compact_string<5, 3> value;
  872. impl::compact_pointer_parent<xml_node_struct, 6> parent;
  873. impl::compact_pointer<xml_node_struct, 8, 0> first_child;
  874. impl::compact_pointer<xml_node_struct, 9> prev_sibling_c;
  875. impl::compact_pointer<xml_node_struct, 10, 0> next_sibling;
  876. impl::compact_pointer<xml_attribute_struct, 11, 0> first_attribute;
  877. };
  878. }
  879. #else
  880. namespace pugi
  881. {
  882. struct xml_attribute_struct
  883. {
  884. xml_attribute_struct(impl::xml_memory_page* page): name(0), value(0), prev_attribute_c(0), next_attribute(0)
  885. {
  886. header = PUGI__GETHEADER_IMPL(this, page, 0);
  887. }
  888. uintptr_t header;
  889. char_t* name;
  890. char_t* value;
  891. xml_attribute_struct* prev_attribute_c;
  892. xml_attribute_struct* next_attribute;
  893. };
  894. struct xml_node_struct
  895. {
  896. xml_node_struct(impl::xml_memory_page* page, xml_node_type type): name(0), value(0), parent(0), first_child(0), prev_sibling_c(0), next_sibling(0), first_attribute(0)
  897. {
  898. header = PUGI__GETHEADER_IMPL(this, page, type);
  899. }
  900. uintptr_t header;
  901. char_t* name;
  902. char_t* value;
  903. xml_node_struct* parent;
  904. xml_node_struct* first_child;
  905. xml_node_struct* prev_sibling_c;
  906. xml_node_struct* next_sibling;
  907. xml_attribute_struct* first_attribute;
  908. };
  909. }
  910. #endif
  911. PUGI__NS_BEGIN
  912. struct xml_extra_buffer
  913. {
  914. char_t* buffer;
  915. xml_extra_buffer* next;
  916. };
  917. struct xml_document_struct: public xml_node_struct, public xml_allocator
  918. {
  919. xml_document_struct(xml_memory_page* page): xml_node_struct(page, node_document), xml_allocator(page), buffer(0), extra_buffers(0)
  920. {
  921. }
  922. const char_t* buffer;
  923. xml_extra_buffer* extra_buffers;
  924. #ifdef PUGIXML_COMPACT
  925. compact_hash_table hash;
  926. #endif
  927. };
  928. template <typename Object> inline xml_allocator& get_allocator(const Object* object)
  929. {
  930. assert(object);
  931. return *PUGI__GETPAGE(object)->allocator;
  932. }
  933. template <typename Object> inline xml_document_struct& get_document(const Object* object)
  934. {
  935. assert(object);
  936. return *static_cast<xml_document_struct*>(PUGI__GETPAGE(object)->allocator);
  937. }
  938. PUGI__NS_END
  939. // Low-level DOM operations
  940. PUGI__NS_BEGIN
  941. inline xml_attribute_struct* allocate_attribute(xml_allocator& alloc)
  942. {
  943. xml_memory_page* page;
  944. void* memory = alloc.allocate_object(sizeof(xml_attribute_struct), page);
  945. if (!memory) return 0;
  946. return new (memory) xml_attribute_struct(page);
  947. }
  948. inline xml_node_struct* allocate_node(xml_allocator& alloc, xml_node_type type)
  949. {
  950. xml_memory_page* page;
  951. void* memory = alloc.allocate_object(sizeof(xml_node_struct), page);
  952. if (!memory) return 0;
  953. return new (memory) xml_node_struct(page, type);
  954. }
  955. inline void destroy_attribute(xml_attribute_struct* a, xml_allocator& alloc)
  956. {
  957. if (a->header & impl::xml_memory_page_name_allocated_mask)
  958. alloc.deallocate_string(a->name);
  959. if (a->header & impl::xml_memory_page_value_allocated_mask)
  960. alloc.deallocate_string(a->value);
  961. alloc.deallocate_memory(a, sizeof(xml_attribute_struct), PUGI__GETPAGE(a));
  962. }
  963. inline void destroy_node(xml_node_struct* n, xml_allocator& alloc)
  964. {
  965. if (n->header & impl::xml_memory_page_name_allocated_mask)
  966. alloc.deallocate_string(n->name);
  967. if (n->header & impl::xml_memory_page_value_allocated_mask)
  968. alloc.deallocate_string(n->value);
  969. for (xml_attribute_struct* attr = n->first_attribute; attr; )
  970. {
  971. xml_attribute_struct* next = attr->next_attribute;
  972. destroy_attribute(attr, alloc);
  973. attr = next;
  974. }
  975. for (xml_node_struct* child = n->first_child; child; )
  976. {
  977. xml_node_struct* next = child->next_sibling;
  978. destroy_node(child, alloc);
  979. child = next;
  980. }
  981. alloc.deallocate_memory(n, sizeof(xml_node_struct), PUGI__GETPAGE(n));
  982. }
  983. inline void append_node(xml_node_struct* child, xml_node_struct* node)
  984. {
  985. child->parent = node;
  986. xml_node_struct* head = node->first_child;
  987. if (head)
  988. {
  989. xml_node_struct* tail = head->prev_sibling_c;
  990. tail->next_sibling = child;
  991. child->prev_sibling_c = tail;
  992. head->prev_sibling_c = child;
  993. }
  994. else
  995. {
  996. node->first_child = child;
  997. child->prev_sibling_c = child;
  998. }
  999. }
  1000. inline void prepend_node(xml_node_struct* child, xml_node_struct* node)
  1001. {
  1002. child->parent = node;
  1003. xml_node_struct* head = node->first_child;
  1004. if (head)
  1005. {
  1006. child->prev_sibling_c = head->prev_sibling_c;
  1007. head->prev_sibling_c = child;
  1008. }
  1009. else
  1010. child->prev_sibling_c = child;
  1011. child->next_sibling = head;
  1012. node->first_child = child;
  1013. }
  1014. inline void insert_node_after(xml_node_struct* child, xml_node_struct* node)
  1015. {
  1016. xml_node_struct* parent = node->parent;
  1017. child->parent = parent;
  1018. if (node->next_sibling)
  1019. node->next_sibling->prev_sibling_c = child;
  1020. else
  1021. parent->first_child->prev_sibling_c = child;
  1022. child->next_sibling = node->next_sibling;
  1023. child->prev_sibling_c = node;
  1024. node->next_sibling = child;
  1025. }
  1026. inline void insert_node_before(xml_node_struct* child, xml_node_struct* node)
  1027. {
  1028. xml_node_struct* parent = node->parent;
  1029. child->parent = parent;
  1030. if (node->prev_sibling_c->next_sibling)
  1031. node->prev_sibling_c->next_sibling = child;
  1032. else
  1033. parent->first_child = child;
  1034. child->prev_sibling_c = node->prev_sibling_c;
  1035. child->next_sibling = node;
  1036. node->prev_sibling_c = child;
  1037. }
  1038. inline void remove_node(xml_node_struct* node)
  1039. {
  1040. xml_node_struct* parent = node->parent;
  1041. if (node->next_sibling)
  1042. node->next_sibling->prev_sibling_c = node->prev_sibling_c;
  1043. else
  1044. parent->first_child->prev_sibling_c = node->prev_sibling_c;
  1045. if (node->prev_sibling_c->next_sibling)
  1046. node->prev_sibling_c->next_sibling = node->next_sibling;
  1047. else
  1048. parent->first_child = node->next_sibling;
  1049. node->parent = 0;
  1050. node->prev_sibling_c = 0;
  1051. node->next_sibling = 0;
  1052. }
  1053. inline void append_attribute(xml_attribute_struct* attr, xml_node_struct* node)
  1054. {
  1055. xml_attribute_struct* head = node->first_attribute;
  1056. if (head)
  1057. {
  1058. xml_attribute_struct* tail = head->prev_attribute_c;
  1059. tail->next_attribute = attr;
  1060. attr->prev_attribute_c = tail;
  1061. head->prev_attribute_c = attr;
  1062. }
  1063. else
  1064. {
  1065. node->first_attribute = attr;
  1066. attr->prev_attribute_c = attr;
  1067. }
  1068. }
  1069. inline void prepend_attribute(xml_attribute_struct* attr, xml_node_struct* node)
  1070. {
  1071. xml_attribute_struct* head = node->first_attribute;
  1072. if (head)
  1073. {
  1074. attr->prev_attribute_c = head->prev_attribute_c;
  1075. head->prev_attribute_c = attr;
  1076. }
  1077. else
  1078. attr->prev_attribute_c = attr;
  1079. attr->next_attribute = head;
  1080. node->first_attribute = attr;
  1081. }
  1082. inline void insert_attribute_after(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node)
  1083. {
  1084. if (place->next_attribute)
  1085. place->next_attribute->prev_attribute_c = attr;
  1086. else
  1087. node->first_attribute->prev_attribute_c = attr;
  1088. attr->next_attribute = place->next_attribute;
  1089. attr->prev_attribute_c = place;
  1090. place->next_attribute = attr;
  1091. }
  1092. inline void insert_attribute_before(xml_attribute_struct* attr, xml_attribute_struct* place, xml_node_struct* node)
  1093. {
  1094. if (place->prev_attribute_c->next_attribute)
  1095. place->prev_attribute_c->next_attribute = attr;
  1096. else
  1097. node->first_attribute = attr;
  1098. attr->prev_attribute_c = place->prev_attribute_c;
  1099. attr->next_attribute = place;
  1100. place->prev_attribute_c = attr;
  1101. }
  1102. inline void remove_attribute(xml_attribute_struct* attr, xml_node_struct* node)
  1103. {
  1104. if (attr->next_attribute)
  1105. attr->next_attribute->prev_attribute_c = attr->prev_attribute_c;
  1106. else
  1107. node->first_attribute->prev_attribute_c = attr->prev_attribute_c;
  1108. if (attr->prev_attribute_c->next_attribute)
  1109. attr->prev_attribute_c->next_attribute = attr->next_attribute;
  1110. else
  1111. node->first_attribute = attr->next_attribute;
  1112. attr->prev_attribute_c = 0;
  1113. attr->next_attribute = 0;
  1114. }
  1115. PUGI__FN_NO_INLINE xml_node_struct* append_new_node(xml_node_struct* node, xml_allocator& alloc, xml_node_type type = node_element)
  1116. {
  1117. if (!alloc.reserve()) return 0;
  1118. xml_node_struct* child = allocate_node(alloc, type);
  1119. if (!child) return 0;
  1120. append_node(child, node);
  1121. return child;
  1122. }
  1123. PUGI__FN_NO_INLINE xml_attribute_struct* append_new_attribute(xml_node_struct* node, xml_allocator& alloc)
  1124. {
  1125. if (!alloc.reserve()) return 0;
  1126. xml_attribute_struct* attr = allocate_attribute(alloc);
  1127. if (!attr) return 0;
  1128. append_attribute(attr, node);
  1129. return attr;
  1130. }
  1131. PUGI__NS_END
  1132. // Helper classes for code generation
  1133. PUGI__NS_BEGIN
  1134. struct opt_false
  1135. {
  1136. enum { value = 0 };
  1137. };
  1138. struct opt_true
  1139. {
  1140. enum { value = 1 };
  1141. };
  1142. PUGI__NS_END
  1143. // Unicode utilities
  1144. PUGI__NS_BEGIN
  1145. inline uint16_t endian_swap(uint16_t value)
  1146. {
  1147. return static_cast<uint16_t>(((value & 0xff) << 8) | (value >> 8));
  1148. }
  1149. inline uint32_t endian_swap(uint32_t value)
  1150. {
  1151. return ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value & 0xff0000) >> 8) | (value >> 24);
  1152. }
  1153. struct utf8_counter
  1154. {
  1155. typedef size_t value_type;
  1156. static value_type low(value_type result, uint32_t ch)
  1157. {
  1158. // U+0000..U+007F
  1159. if (ch < 0x80) return result + 1;
  1160. // U+0080..U+07FF
  1161. else if (ch < 0x800) return result + 2;
  1162. // U+0800..U+FFFF
  1163. else return result + 3;
  1164. }
  1165. static value_type high(value_type result, uint32_t)
  1166. {
  1167. // U+10000..U+10FFFF
  1168. return result + 4;
  1169. }
  1170. };
  1171. struct utf8_writer
  1172. {
  1173. typedef uint8_t* value_type;
  1174. static value_type low(value_type result, uint32_t ch)
  1175. {
  1176. // U+0000..U+007F
  1177. if (ch < 0x80)
  1178. {
  1179. *result = static_cast<uint8_t>(ch);
  1180. return result + 1;
  1181. }
  1182. // U+0080..U+07FF
  1183. else if (ch < 0x800)
  1184. {
  1185. result[0] = static_cast<uint8_t>(0xC0 | (ch >> 6));
  1186. result[1] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  1187. return result + 2;
  1188. }
  1189. // U+0800..U+FFFF
  1190. else
  1191. {
  1192. result[0] = static_cast<uint8_t>(0xE0 | (ch >> 12));
  1193. result[1] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
  1194. result[2] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  1195. return result + 3;
  1196. }
  1197. }
  1198. static value_type high(value_type result, uint32_t ch)
  1199. {
  1200. // U+10000..U+10FFFF
  1201. result[0] = static_cast<uint8_t>(0xF0 | (ch >> 18));
  1202. result[1] = static_cast<uint8_t>(0x80 | ((ch >> 12) & 0x3F));
  1203. result[2] = static_cast<uint8_t>(0x80 | ((ch >> 6) & 0x3F));
  1204. result[3] = static_cast<uint8_t>(0x80 | (ch & 0x3F));
  1205. return result + 4;
  1206. }
  1207. static value_type any(value_type result, uint32_t ch)
  1208. {
  1209. return (ch < 0x10000) ? low(result, ch) : high(result, ch);
  1210. }
  1211. };
  1212. struct utf16_counter
  1213. {
  1214. typedef size_t value_type;
  1215. static value_type low(value_type result, uint32_t)
  1216. {
  1217. return result + 1;
  1218. }
  1219. static value_type high(value_type result, uint32_t)
  1220. {
  1221. return result + 2;
  1222. }
  1223. };
  1224. struct utf16_writer
  1225. {
  1226. typedef uint16_t* value_type;
  1227. static value_type low(value_type result, uint32_t ch)
  1228. {
  1229. *result = static_cast<uint16_t>(ch);
  1230. return result + 1;
  1231. }
  1232. static value_type high(value_type result, uint32_t ch)
  1233. {
  1234. uint32_t msh = static_cast<uint32_t>(ch - 0x10000) >> 10;
  1235. uint32_t lsh = static_cast<uint32_t>(ch - 0x10000) & 0x3ff;
  1236. result[0] = static_cast<uint16_t>(0xD800 + msh);
  1237. result[1] = static_cast<uint16_t>(0xDC00 + lsh);
  1238. return result + 2;
  1239. }
  1240. static value_type any(value_type result, uint32_t ch)
  1241. {
  1242. return (ch < 0x10000) ? low(result, ch) : high(result, ch);
  1243. }
  1244. };
  1245. struct utf32_counter
  1246. {
  1247. typedef size_t value_type;
  1248. static value_type low(value_type result, uint32_t)
  1249. {
  1250. return result + 1;
  1251. }
  1252. static value_type high(value_type result, uint32_t)
  1253. {
  1254. return result + 1;
  1255. }
  1256. };
  1257. struct utf32_writer
  1258. {
  1259. typedef uint32_t* value_type;
  1260. static value_type low(value_type result, uint32_t ch)
  1261. {
  1262. *result = ch;
  1263. return result + 1;
  1264. }
  1265. static value_type high(value_type result, uint32_t ch)
  1266. {
  1267. *result = ch;
  1268. return result + 1;
  1269. }
  1270. static value_type any(value_type result, uint32_t ch)
  1271. {
  1272. *result = ch;
  1273. return result + 1;
  1274. }
  1275. };
  1276. struct latin1_writer
  1277. {
  1278. typedef uint8_t* value_type;
  1279. static value_type low(value_type result, uint32_t ch)
  1280. {
  1281. *result = static_cast<uint8_t>(ch > 255 ? '?' : ch);
  1282. return result + 1;
  1283. }
  1284. static value_type high(value_type result, uint32_t ch)
  1285. {
  1286. (void)ch;
  1287. *result = '?';
  1288. return result + 1;
  1289. }
  1290. };
  1291. struct utf8_decoder
  1292. {
  1293. typedef uint8_t type;
  1294. template <typename Traits> static inline typename Traits::value_type process(const uint8_t* data, size_t size, typename Traits::value_type result, Traits)
  1295. {
  1296. const uint8_t utf8_byte_mask = 0x3f;
  1297. while (size)
  1298. {
  1299. uint8_t lead = *data;
  1300. // 0xxxxxxx -> U+0000..U+007F
  1301. if (lead < 0x80)
  1302. {
  1303. result = Traits::low(result, lead);
  1304. data += 1;
  1305. size -= 1;
  1306. // process aligned single-byte (ascii) blocks
  1307. if ((reinterpret_cast<uintptr_t>(data) & 3) == 0)
  1308. {
  1309. // round-trip through void* to silence 'cast increases required alignment of target type' warnings
  1310. while (size >= 4 && (*static_cast<const uint32_t*>(static_cast<const void*>(data)) & 0x80808080) == 0)
  1311. {
  1312. result = Traits::low(result, data[0]);
  1313. result = Traits::low(result, data[1]);
  1314. result = Traits::low(result, data[2]);
  1315. result = Traits::low(result, data[3]);
  1316. data += 4;
  1317. size -= 4;
  1318. }
  1319. }
  1320. }
  1321. // 110xxxxx -> U+0080..U+07FF
  1322. else if (static_cast<unsigned int>(lead - 0xC0) < 0x20 && size >= 2 && (data[1] & 0xc0) == 0x80)
  1323. {
  1324. result = Traits::low(result, ((lead & ~0xC0) << 6) | (data[1] & utf8_byte_mask));
  1325. data += 2;
  1326. size -= 2;
  1327. }
  1328. // 1110xxxx -> U+0800-U+FFFF
  1329. else if (static_cast<unsigned int>(lead - 0xE0) < 0x10 && size >= 3 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80)
  1330. {
  1331. result = Traits::low(result, ((lead & ~0xE0) << 12) | ((data[1] & utf8_byte_mask) << 6) | (data[2] & utf8_byte_mask));
  1332. data += 3;
  1333. size -= 3;
  1334. }
  1335. // 11110xxx -> U+10000..U+10FFFF
  1336. else if (static_cast<unsigned int>(lead - 0xF0) < 0x08 && size >= 4 && (data[1] & 0xc0) == 0x80 && (data[2] & 0xc0) == 0x80 && (data[3] & 0xc0) == 0x80)
  1337. {
  1338. result = Traits::high(result, ((lead & ~0xF0) << 18) | ((data[1] & utf8_byte_mask) << 12) | ((data[2] & utf8_byte_mask) << 6) | (data[3] & utf8_byte_mask));
  1339. data += 4;
  1340. size -= 4;
  1341. }
  1342. // 10xxxxxx or 11111xxx -> invalid
  1343. else
  1344. {
  1345. data += 1;
  1346. size -= 1;
  1347. }
  1348. }
  1349. return result;
  1350. }
  1351. };
  1352. template <typename opt_swap> struct utf16_decoder
  1353. {
  1354. typedef uint16_t type;
  1355. template <typename Traits> static inline typename Traits::value_type process(const uint16_t* data, size_t size, typename Traits::value_type result, Traits)
  1356. {
  1357. while (size)
  1358. {
  1359. uint16_t lead = opt_swap::value ? endian_swap(*data) : *data;
  1360. // U+0000..U+D7FF
  1361. if (lead < 0xD800)
  1362. {
  1363. result = Traits::low(result, lead);
  1364. data += 1;
  1365. size -= 1;
  1366. }
  1367. // U+E000..U+FFFF
  1368. else if (static_cast<unsigned int>(lead - 0xE000) < 0x2000)
  1369. {
  1370. result = Traits::low(result, lead);
  1371. data += 1;
  1372. size -= 1;
  1373. }
  1374. // surrogate pair lead
  1375. else if (static_cast<unsigned int>(lead - 0xD800) < 0x400 && size >= 2)
  1376. {
  1377. uint16_t next = opt_swap::value ? endian_swap(data[1]) : data[1];
  1378. if (static_cast<unsigned int>(next - 0xDC00) < 0x400)
  1379. {
  1380. result = Traits::high(result, 0x10000 + ((lead & 0x3ff) << 10) + (next & 0x3ff));
  1381. data += 2;
  1382. size -= 2;
  1383. }
  1384. else
  1385. {
  1386. data += 1;
  1387. size -= 1;
  1388. }
  1389. }
  1390. else
  1391. {
  1392. data += 1;
  1393. size -= 1;
  1394. }
  1395. }
  1396. return result;
  1397. }
  1398. };
  1399. template <typename opt_swap> struct utf32_decoder
  1400. {
  1401. typedef uint32_t type;
  1402. template <typename Traits> static inline typename Traits::value_type process(const uint32_t* data, size_t size, typename Traits::value_type result, Traits)
  1403. {
  1404. while (size)
  1405. {
  1406. uint32_t lead = opt_swap::value ? endian_swap(*data) : *data;
  1407. // U+0000..U+FFFF
  1408. if (lead < 0x10000)
  1409. {
  1410. result = Traits::low(result, lead);
  1411. data += 1;
  1412. size -= 1;
  1413. }
  1414. // U+10000..U+10FFFF
  1415. else
  1416. {
  1417. result = Traits::high(result, lead);
  1418. data += 1;
  1419. size -= 1;
  1420. }
  1421. }
  1422. return result;
  1423. }
  1424. };
  1425. struct latin1_decoder
  1426. {
  1427. typedef uint8_t type;
  1428. template <typename Traits> static inline typename Traits::value_type process(const uint8_t* data, size_t size, typename Traits::value_type result, Traits)
  1429. {
  1430. while (size)
  1431. {
  1432. result = Traits::low(result, *data);
  1433. data += 1;
  1434. size -= 1;
  1435. }
  1436. return result;
  1437. }
  1438. };
  1439. template <size_t size> struct wchar_selector;
  1440. template <> struct wchar_selector<2>
  1441. {
  1442. typedef uint16_t type;
  1443. typedef utf16_counter counter;
  1444. typedef utf16_writer writer;
  1445. typedef utf16_decoder<opt_false> decoder;
  1446. };
  1447. template <> struct wchar_selector<4>
  1448. {
  1449. typedef uint32_t type;
  1450. typedef utf32_counter counter;
  1451. typedef utf32_writer writer;
  1452. typedef utf32_decoder<opt_false> decoder;
  1453. };
  1454. typedef wchar_selector<sizeof(wchar_t)>::counter wchar_counter;
  1455. typedef wchar_selector<sizeof(wchar_t)>::writer wchar_writer;
  1456. struct wchar_decoder
  1457. {
  1458. typedef wchar_t type;
  1459. template <typename Traits> static inline typename Traits::value_type process(const wchar_t* data, size_t size, typename Traits::value_type result, Traits traits)
  1460. {
  1461. typedef wchar_selector<sizeof(wchar_t)>::decoder decoder;
  1462. return decoder::process(reinterpret_cast<const typename decoder::type*>(data), size, result, traits);
  1463. }
  1464. };
  1465. #ifdef PUGIXML_WCHAR_MODE
  1466. PUGI__FN void convert_wchar_endian_swap(wchar_t* result, const wchar_t* data, size_t length)
  1467. {
  1468. for (size_t i = 0; i < length; ++i)
  1469. result[i] = static_cast<wchar_t>(endian_swap(static_cast<wchar_selector<sizeof(wchar_t)>::type>(data[i])));
  1470. }
  1471. #endif
  1472. PUGI__NS_END
  1473. PUGI__NS_BEGIN
  1474. enum chartype_t
  1475. {
  1476. ct_parse_pcdata = 1, // \0, &, \r, <
  1477. ct_parse_attr = 2, // \0, &, \r, ', "
  1478. ct_parse_attr_ws = 4, // \0, &, \r, ', ", \n, tab
  1479. ct_space = 8, // \r, \n, space, tab
  1480. ct_parse_cdata = 16, // \0, ], >, \r
  1481. ct_parse_comment = 32, // \0, -, >, \r
  1482. ct_symbol = 64, // Any symbol > 127, a-z, A-Z, 0-9, _, :, -, .
  1483. ct_start_symbol = 128 // Any symbol > 127, a-z, A-Z, _, :
  1484. };
  1485. static const unsigned char chartype_table[256] =
  1486. {
  1487. 55, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 0, 0, 63, 0, 0, // 0-15
  1488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
  1489. 8, 0, 6, 0, 0, 0, 7, 6, 0, 0, 0, 0, 0, 96, 64, 0, // 32-47
  1490. 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 192, 0, 1, 0, 48, 0, // 48-63
  1491. 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 64-79
  1492. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 16, 0, 192, // 80-95
  1493. 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 96-111
  1494. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 0, 0, 0, 0, // 112-127
  1495. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, // 128+
  1496. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  1497. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  1498. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  1499. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  1500. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  1501. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192,
  1502. 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192
  1503. };
  1504. enum chartypex_t
  1505. {
  1506. ctx_special_pcdata = 1, // Any symbol >= 0 and < 32 (except \t, \r, \n), &, <, >
  1507. ctx_special_attr = 2, // Any symbol >= 0 and < 32, &, <, ", '
  1508. ctx_start_symbol = 4, // Any symbol > 127, a-z, A-Z, _
  1509. ctx_digit = 8, // 0-9
  1510. ctx_symbol = 16 // Any symbol > 127, a-z, A-Z, 0-9, _, -, .
  1511. };
  1512. static const unsigned char chartypex_table[256] =
  1513. {
  1514. 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, // 0-15
  1515. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 16-31
  1516. 0, 0, 2, 0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 16, 16, 0, // 32-47
  1517. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 3, 0, 1, 0, // 48-63
  1518. 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 64-79
  1519. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 20, // 80-95
  1520. 0, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 96-111
  1521. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, // 112-127
  1522. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, // 128+
  1523. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1524. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1525. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1526. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1527. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1528. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  1529. 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20
  1530. };
  1531. #ifdef PUGIXML_WCHAR_MODE
  1532. #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) ((static_cast<unsigned int>(c) < 128 ? table[static_cast<unsigned int>(c)] : table[128]) & (ct))
  1533. #else
  1534. #define PUGI__IS_CHARTYPE_IMPL(c, ct, table) (table[static_cast<unsigned char>(c)] & (ct))
  1535. #endif
  1536. #define PUGI__IS_CHARTYPE(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartype_table)
  1537. #define PUGI__IS_CHARTYPEX(c, ct) PUGI__IS_CHARTYPE_IMPL(c, ct, chartypex_table)
  1538. PUGI__FN bool is_little_endian()
  1539. {
  1540. unsigned int ui = 1;
  1541. return *reinterpret_cast<unsigned char*>(&ui) == 1;
  1542. }
  1543. PUGI__FN xml_encoding get_wchar_encoding()
  1544. {
  1545. PUGI__STATIC_ASSERT(sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4);
  1546. if (sizeof(wchar_t) == 2)
  1547. return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1548. else
  1549. return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1550. }
  1551. PUGI__FN bool parse_declaration_encoding(const uint8_t* data, size_t size, const uint8_t*& out_encoding, size_t& out_length)
  1552. {
  1553. #define PUGI__SCANCHAR(ch) { if (offset >= size || data[offset] != ch) return false; offset++; }
  1554. #define PUGI__SCANCHARTYPE(ct) { while (offset < size && PUGI__IS_CHARTYPE(data[offset], ct)) offset++; }
  1555. // check if we have a non-empty XML declaration
  1556. if (size < 6 || !((data[0] == '<') & (data[1] == '?') & (data[2] == 'x') & (data[3] == 'm') & (data[4] == 'l') && PUGI__IS_CHARTYPE(data[5], ct_space)))
  1557. return false;
  1558. // scan XML declaration until the encoding field
  1559. for (size_t i = 6; i + 1 < size; ++i)
  1560. {
  1561. // declaration can not contain ? in quoted values
  1562. if (data[i] == '?')
  1563. return false;
  1564. if (data[i] == 'e' && data[i + 1] == 'n')
  1565. {
  1566. size_t offset = i;
  1567. // encoding follows the version field which can't contain 'en' so this has to be the encoding if XML is well formed
  1568. PUGI__SCANCHAR('e'); PUGI__SCANCHAR('n'); PUGI__SCANCHAR('c'); PUGI__SCANCHAR('o');
  1569. PUGI__SCANCHAR('d'); PUGI__SCANCHAR('i'); PUGI__SCANCHAR('n'); PUGI__SCANCHAR('g');
  1570. // S? = S?
  1571. PUGI__SCANCHARTYPE(ct_space);
  1572. PUGI__SCANCHAR('=');
  1573. PUGI__SCANCHARTYPE(ct_space);
  1574. // the only two valid delimiters are ' and "
  1575. uint8_t delimiter = (offset < size && data[offset] == '"') ? '"' : '\'';
  1576. PUGI__SCANCHAR(delimiter);
  1577. size_t start = offset;
  1578. out_encoding = data + offset;
  1579. PUGI__SCANCHARTYPE(ct_symbol);
  1580. out_length = offset - start;
  1581. PUGI__SCANCHAR(delimiter);
  1582. return true;
  1583. }
  1584. }
  1585. return false;
  1586. #undef PUGI__SCANCHAR
  1587. #undef PUGI__SCANCHARTYPE
  1588. }
  1589. PUGI__FN xml_encoding guess_buffer_encoding(const uint8_t* data, size_t size)
  1590. {
  1591. // skip encoding autodetection if input buffer is too small
  1592. if (size < 4) return encoding_utf8;
  1593. uint8_t d0 = data[0], d1 = data[1], d2 = data[2], d3 = data[3];
  1594. // look for BOM in first few bytes
  1595. if (d0 == 0 && d1 == 0 && d2 == 0xfe && d3 == 0xff) return encoding_utf32_be;
  1596. if (d0 == 0xff && d1 == 0xfe && d2 == 0 && d3 == 0) return encoding_utf32_le;
  1597. if (d0 == 0xfe && d1 == 0xff) return encoding_utf16_be;
  1598. if (d0 == 0xff && d1 == 0xfe) return encoding_utf16_le;
  1599. if (d0 == 0xef && d1 == 0xbb && d2 == 0xbf) return encoding_utf8;
  1600. // look for <, <? or <?xm in various encodings
  1601. if (d0 == 0 && d1 == 0 && d2 == 0 && d3 == 0x3c) return encoding_utf32_be;
  1602. if (d0 == 0x3c && d1 == 0 && d2 == 0 && d3 == 0) return encoding_utf32_le;
  1603. if (d0 == 0 && d1 == 0x3c && d2 == 0 && d3 == 0x3f) return encoding_utf16_be;
  1604. if (d0 == 0x3c && d1 == 0 && d2 == 0x3f && d3 == 0) return encoding_utf16_le;
  1605. // look for utf16 < followed by node name (this may fail, but is better than utf8 since it's zero terminated so early)
  1606. if (d0 == 0 && d1 == 0x3c) return encoding_utf16_be;
  1607. if (d0 == 0x3c && d1 == 0) return encoding_utf16_le;
  1608. // no known BOM detected; parse declaration
  1609. const uint8_t* enc = 0;
  1610. size_t enc_length = 0;
  1611. if (d0 == 0x3c && d1 == 0x3f && d2 == 0x78 && d3 == 0x6d && parse_declaration_encoding(data, size, enc, enc_length))
  1612. {
  1613. // iso-8859-1 (case-insensitive)
  1614. if (enc_length == 10
  1615. && (enc[0] | ' ') == 'i' && (enc[1] | ' ') == 's' && (enc[2] | ' ') == 'o'
  1616. && enc[3] == '-' && enc[4] == '8' && enc[5] == '8' && enc[6] == '5' && enc[7] == '9'
  1617. && enc[8] == '-' && enc[9] == '1')
  1618. return encoding_latin1;
  1619. // latin1 (case-insensitive)
  1620. if (enc_length == 6
  1621. && (enc[0] | ' ') == 'l' && (enc[1] | ' ') == 'a' && (enc[2] | ' ') == 't'
  1622. && (enc[3] | ' ') == 'i' && (enc[4] | ' ') == 'n'
  1623. && enc[5] == '1')
  1624. return encoding_latin1;
  1625. }
  1626. return encoding_utf8;
  1627. }
  1628. PUGI__FN xml_encoding get_buffer_encoding(xml_encoding encoding, const void* contents, size_t size)
  1629. {
  1630. // replace wchar encoding with utf implementation
  1631. if (encoding == encoding_wchar) return get_wchar_encoding();
  1632. // replace utf16 encoding with utf16 with specific endianness
  1633. if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1634. // replace utf32 encoding with utf32 with specific endianness
  1635. if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1636. // only do autodetection if no explicit encoding is requested
  1637. if (encoding != encoding_auto) return encoding;
  1638. // try to guess encoding (based on XML specification, Appendix F.1)
  1639. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1640. return guess_buffer_encoding(data, size);
  1641. }
  1642. PUGI__FN bool get_mutable_buffer(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1643. {
  1644. size_t length = size / sizeof(char_t);
  1645. if (is_mutable)
  1646. {
  1647. out_buffer = static_cast<char_t*>(const_cast<void*>(contents));
  1648. out_length = length;
  1649. }
  1650. else
  1651. {
  1652. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1653. if (!buffer) return false;
  1654. if (contents)
  1655. memcpy(buffer, contents, length * sizeof(char_t));
  1656. else
  1657. assert(length == 0);
  1658. buffer[length] = 0;
  1659. out_buffer = buffer;
  1660. out_length = length + 1;
  1661. }
  1662. return true;
  1663. }
  1664. #ifdef PUGIXML_WCHAR_MODE
  1665. PUGI__FN bool need_endian_swap_utf(xml_encoding le, xml_encoding re)
  1666. {
  1667. return (le == encoding_utf16_be && re == encoding_utf16_le) || (le == encoding_utf16_le && re == encoding_utf16_be) ||
  1668. (le == encoding_utf32_be && re == encoding_utf32_le) || (le == encoding_utf32_le && re == encoding_utf32_be);
  1669. }
  1670. PUGI__FN bool convert_buffer_endian_swap(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1671. {
  1672. const char_t* data = static_cast<const char_t*>(contents);
  1673. size_t length = size / sizeof(char_t);
  1674. if (is_mutable)
  1675. {
  1676. char_t* buffer = const_cast<char_t*>(data);
  1677. convert_wchar_endian_swap(buffer, data, length);
  1678. out_buffer = buffer;
  1679. out_length = length;
  1680. }
  1681. else
  1682. {
  1683. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1684. if (!buffer) return false;
  1685. convert_wchar_endian_swap(buffer, data, length);
  1686. buffer[length] = 0;
  1687. out_buffer = buffer;
  1688. out_length = length + 1;
  1689. }
  1690. return true;
  1691. }
  1692. template <typename D> PUGI__FN bool convert_buffer_generic(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, D)
  1693. {
  1694. const typename D::type* data = static_cast<const typename D::type*>(contents);
  1695. size_t data_length = size / sizeof(typename D::type);
  1696. // first pass: get length in wchar_t units
  1697. size_t length = D::process(data, data_length, 0, wchar_counter());
  1698. // allocate buffer of suitable length
  1699. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1700. if (!buffer) return false;
  1701. // second pass: convert utf16 input to wchar_t
  1702. wchar_writer::value_type obegin = reinterpret_cast<wchar_writer::value_type>(buffer);
  1703. wchar_writer::value_type oend = D::process(data, data_length, obegin, wchar_writer());
  1704. assert(oend == obegin + length);
  1705. *oend = 0;
  1706. out_buffer = buffer;
  1707. out_length = length + 1;
  1708. return true;
  1709. }
  1710. 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)
  1711. {
  1712. // get native encoding
  1713. xml_encoding wchar_encoding = get_wchar_encoding();
  1714. // fast path: no conversion required
  1715. if (encoding == wchar_encoding)
  1716. return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1717. // only endian-swapping is required
  1718. if (need_endian_swap_utf(encoding, wchar_encoding))
  1719. return convert_buffer_endian_swap(out_buffer, out_length, contents, size, is_mutable);
  1720. // source encoding is utf8
  1721. if (encoding == encoding_utf8)
  1722. return convert_buffer_generic(out_buffer, out_length, contents, size, utf8_decoder());
  1723. // source encoding is utf16
  1724. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  1725. {
  1726. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1727. return (native_encoding == encoding) ?
  1728. convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_false>()) :
  1729. convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_true>());
  1730. }
  1731. // source encoding is utf32
  1732. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  1733. {
  1734. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1735. return (native_encoding == encoding) ?
  1736. convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_false>()) :
  1737. convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_true>());
  1738. }
  1739. // source encoding is latin1
  1740. if (encoding == encoding_latin1)
  1741. return convert_buffer_generic(out_buffer, out_length, contents, size, latin1_decoder());
  1742. assert(false && "Invalid encoding"); // unreachable
  1743. return false;
  1744. }
  1745. #else
  1746. template <typename D> PUGI__FN bool convert_buffer_generic(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, D)
  1747. {
  1748. const typename D::type* data = static_cast<const typename D::type*>(contents);
  1749. size_t data_length = size / sizeof(typename D::type);
  1750. // first pass: get length in utf8 units
  1751. size_t length = D::process(data, data_length, 0, utf8_counter());
  1752. // allocate buffer of suitable length
  1753. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1754. if (!buffer) return false;
  1755. // second pass: convert utf16 input to utf8
  1756. uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
  1757. uint8_t* oend = D::process(data, data_length, obegin, utf8_writer());
  1758. assert(oend == obegin + length);
  1759. *oend = 0;
  1760. out_buffer = buffer;
  1761. out_length = length + 1;
  1762. return true;
  1763. }
  1764. PUGI__FN size_t get_latin1_7bit_prefix_length(const uint8_t* data, size_t size)
  1765. {
  1766. for (size_t i = 0; i < size; ++i)
  1767. if (data[i] > 127)
  1768. return i;
  1769. return size;
  1770. }
  1771. PUGI__FN bool convert_buffer_latin1(char_t*& out_buffer, size_t& out_length, const void* contents, size_t size, bool is_mutable)
  1772. {
  1773. const uint8_t* data = static_cast<const uint8_t*>(contents);
  1774. size_t data_length = size;
  1775. // get size of prefix that does not need utf8 conversion
  1776. size_t prefix_length = get_latin1_7bit_prefix_length(data, data_length);
  1777. assert(prefix_length <= data_length);
  1778. const uint8_t* postfix = data + prefix_length;
  1779. size_t postfix_length = data_length - prefix_length;
  1780. // if no conversion is needed, just return the original buffer
  1781. if (postfix_length == 0) return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1782. // first pass: get length in utf8 units
  1783. size_t length = prefix_length + latin1_decoder::process(postfix, postfix_length, 0, utf8_counter());
  1784. // allocate buffer of suitable length
  1785. char_t* buffer = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  1786. if (!buffer) return false;
  1787. // second pass: convert latin1 input to utf8
  1788. memcpy(buffer, data, prefix_length);
  1789. uint8_t* obegin = reinterpret_cast<uint8_t*>(buffer);
  1790. uint8_t* oend = latin1_decoder::process(postfix, postfix_length, obegin + prefix_length, utf8_writer());
  1791. assert(oend == obegin + length);
  1792. *oend = 0;
  1793. out_buffer = buffer;
  1794. out_length = length + 1;
  1795. return true;
  1796. }
  1797. 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)
  1798. {
  1799. // fast path: no conversion required
  1800. if (encoding == encoding_utf8)
  1801. return get_mutable_buffer(out_buffer, out_length, contents, size, is_mutable);
  1802. // source encoding is utf16
  1803. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  1804. {
  1805. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  1806. return (native_encoding == encoding) ?
  1807. convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_false>()) :
  1808. convert_buffer_generic(out_buffer, out_length, contents, size, utf16_decoder<opt_true>());
  1809. }
  1810. // source encoding is utf32
  1811. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  1812. {
  1813. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  1814. return (native_encoding == encoding) ?
  1815. convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_false>()) :
  1816. convert_buffer_generic(out_buffer, out_length, contents, size, utf32_decoder<opt_true>());
  1817. }
  1818. // source encoding is latin1
  1819. if (encoding == encoding_latin1)
  1820. return convert_buffer_latin1(out_buffer, out_length, contents, size, is_mutable);
  1821. assert(false && "Invalid encoding"); // unreachable
  1822. return false;
  1823. }
  1824. #endif
  1825. PUGI__FN size_t as_utf8_begin(const wchar_t* str, size_t length)
  1826. {
  1827. // get length in utf8 characters
  1828. return wchar_decoder::process(str, length, 0, utf8_counter());
  1829. }
  1830. PUGI__FN void as_utf8_end(char* buffer, size_t size, const wchar_t* str, size_t length)
  1831. {
  1832. // convert to utf8
  1833. uint8_t* begin = reinterpret_cast<uint8_t*>(buffer);
  1834. uint8_t* end = wchar_decoder::process(str, length, begin, utf8_writer());
  1835. assert(begin + size == end);
  1836. (void)!end;
  1837. (void)!size;
  1838. }
  1839. #ifndef PUGIXML_NO_STL
  1840. PUGI__FN std::string as_utf8_impl(const wchar_t* str, size_t length)
  1841. {
  1842. // first pass: get length in utf8 characters
  1843. size_t size = as_utf8_begin(str, length);
  1844. // allocate resulting string
  1845. std::string result;
  1846. result.resize(size);
  1847. // second pass: convert to utf8
  1848. if (size > 0) as_utf8_end(&result[0], size, str, length);
  1849. return result;
  1850. }
  1851. PUGI__FN std::basic_string<wchar_t> as_wide_impl(const char* str, size_t size)
  1852. {
  1853. const uint8_t* data = reinterpret_cast<const uint8_t*>(str);
  1854. // first pass: get length in wchar_t units
  1855. size_t length = utf8_decoder::process(data, size, 0, wchar_counter());
  1856. // allocate resulting string
  1857. std::basic_string<wchar_t> result;
  1858. result.resize(length);
  1859. // second pass: convert to wchar_t
  1860. if (length > 0)
  1861. {
  1862. wchar_writer::value_type begin = reinterpret_cast<wchar_writer::value_type>(&result[0]);
  1863. wchar_writer::value_type end = utf8_decoder::process(data, size, begin, wchar_writer());
  1864. assert(begin + length == end);
  1865. (void)!end;
  1866. }
  1867. return result;
  1868. }
  1869. #endif
  1870. template <typename Header>
  1871. inline bool strcpy_insitu_allow(size_t length, const Header& header, uintptr_t header_mask, char_t* target)
  1872. {
  1873. // never reuse shared memory
  1874. if (header & xml_memory_page_contents_shared_mask) return false;
  1875. size_t target_length = strlength(target);
  1876. // always reuse document buffer memory if possible
  1877. if ((header & header_mask) == 0) return target_length >= length;
  1878. // reuse heap memory if waste is not too great
  1879. const size_t reuse_threshold = 32;
  1880. return target_length >= length && (target_length < reuse_threshold || target_length - length < target_length / 2);
  1881. }
  1882. template <typename String, typename Header>
  1883. PUGI__FN bool strcpy_insitu(String& dest, Header& header, uintptr_t header_mask, const char_t* source, size_t source_length)
  1884. {
  1885. if (source_length == 0)
  1886. {
  1887. // empty string and null pointer are equivalent, so just deallocate old memory
  1888. xml_allocator* alloc = PUGI__GETPAGE_IMPL(header)->allocator;
  1889. if (header & header_mask) alloc->deallocate_string(dest);
  1890. // mark the string as not allocated
  1891. dest = 0;
  1892. header &= ~header_mask;
  1893. return true;
  1894. }
  1895. else if (dest && strcpy_insitu_allow(source_length, header, header_mask, dest))
  1896. {
  1897. // we can reuse old buffer, so just copy the new data (including zero terminator)
  1898. memcpy(dest, source, source_length * sizeof(char_t));
  1899. dest[source_length] = 0;
  1900. return true;
  1901. }
  1902. else
  1903. {
  1904. xml_allocator* alloc = PUGI__GETPAGE_IMPL(header)->allocator;
  1905. if (!alloc->reserve()) return false;
  1906. // allocate new buffer
  1907. char_t* buf = alloc->allocate_string(source_length + 1);
  1908. if (!buf) return false;
  1909. // copy the string (including zero terminator)
  1910. memcpy(buf, source, source_length * sizeof(char_t));
  1911. buf[source_length] = 0;
  1912. // deallocate old buffer (*after* the above to protect against overlapping memory and/or allocation failures)
  1913. if (header & header_mask) alloc->deallocate_string(dest);
  1914. // the string is now allocated, so set the flag
  1915. dest = buf;
  1916. header |= header_mask;
  1917. return true;
  1918. }
  1919. }
  1920. struct gap
  1921. {
  1922. char_t* end;
  1923. size_t size;
  1924. gap(): end(0), size(0)
  1925. {
  1926. }
  1927. // Push new gap, move s count bytes further (skipping the gap).
  1928. // Collapse previous gap.
  1929. void push(char_t*& s, size_t count)
  1930. {
  1931. if (end) // there was a gap already; collapse it
  1932. {
  1933. // Move [old_gap_end, new_gap_start) to [old_gap_start, ...)
  1934. assert(s >= end);
  1935. memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
  1936. }
  1937. s += count; // end of current gap
  1938. // "merge" two gaps
  1939. end = s;
  1940. size += count;
  1941. }
  1942. // Collapse all gaps, return past-the-end pointer
  1943. char_t* flush(char_t* s)
  1944. {
  1945. if (end)
  1946. {
  1947. // Move [old_gap_end, current_pos) to [old_gap_start, ...)
  1948. assert(s >= end);
  1949. memmove(end - size, end, reinterpret_cast<char*>(s) - reinterpret_cast<char*>(end));
  1950. return s - size;
  1951. }
  1952. else return s;
  1953. }
  1954. };
  1955. PUGI__FN char_t* strconv_escape(char_t* s, gap& g)
  1956. {
  1957. char_t* stre = s + 1;
  1958. switch (*stre)
  1959. {
  1960. case '#': // &#...
  1961. {
  1962. unsigned int ucsc = 0;
  1963. if (stre[1] == 'x') // &#x... (hex code)
  1964. {
  1965. stre += 2;
  1966. char_t ch = *stre;
  1967. if (ch == ';') return stre;
  1968. for (;;)
  1969. {
  1970. if (static_cast<unsigned int>(ch - '0') <= 9)
  1971. ucsc = 16 * ucsc + (ch - '0');
  1972. else if (static_cast<unsigned int>((ch | ' ') - 'a') <= 5)
  1973. ucsc = 16 * ucsc + ((ch | ' ') - 'a' + 10);
  1974. else if (ch == ';')
  1975. break;
  1976. else // cancel
  1977. return stre;
  1978. ch = *++stre;
  1979. }
  1980. ++stre;
  1981. }
  1982. else // &#... (dec code)
  1983. {
  1984. char_t ch = *++stre;
  1985. if (ch == ';') return stre;
  1986. for (;;)
  1987. {
  1988. if (static_cast<unsigned int>(ch - '0') <= 9)
  1989. ucsc = 10 * ucsc + (ch - '0');
  1990. else if (ch == ';')
  1991. break;
  1992. else // cancel
  1993. return stre;
  1994. ch = *++stre;
  1995. }
  1996. ++stre;
  1997. }
  1998. #ifdef PUGIXML_WCHAR_MODE
  1999. s = reinterpret_cast<char_t*>(wchar_writer::any(reinterpret_cast<wchar_writer::value_type>(s), ucsc));
  2000. #else
  2001. s = reinterpret_cast<char_t*>(utf8_writer::any(reinterpret_cast<uint8_t*>(s), ucsc));
  2002. #endif
  2003. g.push(s, stre - s);
  2004. return stre;
  2005. }
  2006. case 'a': // &a
  2007. {
  2008. ++stre;
  2009. if (*stre == 'm') // &am
  2010. {
  2011. if (*++stre == 'p' && *++stre == ';') // &amp;
  2012. {
  2013. *s++ = '&';
  2014. ++stre;
  2015. g.push(s, stre - s);
  2016. return stre;
  2017. }
  2018. }
  2019. else if (*stre == 'p') // &ap
  2020. {
  2021. if (*++stre == 'o' && *++stre == 's' && *++stre == ';') // &apos;
  2022. {
  2023. *s++ = '\'';
  2024. ++stre;
  2025. g.push(s, stre - s);
  2026. return stre;
  2027. }
  2028. }
  2029. break;
  2030. }
  2031. case 'g': // &g
  2032. {
  2033. if (*++stre == 't' && *++stre == ';') // &gt;
  2034. {
  2035. *s++ = '>';
  2036. ++stre;
  2037. g.push(s, stre - s);
  2038. return stre;
  2039. }
  2040. break;
  2041. }
  2042. case 'l': // &l
  2043. {
  2044. if (*++stre == 't' && *++stre == ';') // &lt;
  2045. {
  2046. *s++ = '<';
  2047. ++stre;
  2048. g.push(s, stre - s);
  2049. return stre;
  2050. }
  2051. break;
  2052. }
  2053. case 'q': // &q
  2054. {
  2055. if (*++stre == 'u' && *++stre == 'o' && *++stre == 't' && *++stre == ';') // &quot;
  2056. {
  2057. *s++ = '"';
  2058. ++stre;
  2059. g.push(s, stre - s);
  2060. return stre;
  2061. }
  2062. break;
  2063. }
  2064. default:
  2065. break;
  2066. }
  2067. return stre;
  2068. }
  2069. // Parser utilities
  2070. #define PUGI__ENDSWITH(c, e) ((c) == (e) || ((c) == 0 && endch == (e)))
  2071. #define PUGI__SKIPWS() { while (PUGI__IS_CHARTYPE(*s, ct_space)) ++s; }
  2072. #define PUGI__OPTSET(OPT) ( optmsk & (OPT) )
  2073. #define PUGI__PUSHNODE(TYPE) { cursor = append_new_node(cursor, *alloc, TYPE); if (!cursor) PUGI__THROW_ERROR(status_out_of_memory, s); }
  2074. #define PUGI__POPNODE() { cursor = cursor->parent; }
  2075. #define PUGI__SCANFOR(X) { while (*s != 0 && !(X)) ++s; }
  2076. #define PUGI__SCANWHILE(X) { while (X) ++s; }
  2077. #define PUGI__SCANWHILE_UNROLL(X) { for (;;) { char_t ss = s[0]; if (PUGI__UNLIKELY(!(X))) { break; } ss = s[1]; if (PUGI__UNLIKELY(!(X))) { s += 1; break; } ss = s[2]; if (PUGI__UNLIKELY(!(X))) { s += 2; break; } ss = s[3]; if (PUGI__UNLIKELY(!(X))) { s += 3; break; } s += 4; } }
  2078. #define PUGI__ENDSEG() { ch = *s; *s = 0; ++s; }
  2079. #define PUGI__THROW_ERROR(err, m) return error_offset = m, error_status = err, static_cast<char_t*>(0)
  2080. #define PUGI__CHECK_ERROR(err, m) { if (*s == 0) PUGI__THROW_ERROR(err, m); }
  2081. PUGI__FN char_t* strconv_comment(char_t* s, char_t endch)
  2082. {
  2083. gap g;
  2084. while (true)
  2085. {
  2086. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_comment));
  2087. if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  2088. {
  2089. *s++ = '\n'; // replace first one with 0x0a
  2090. if (*s == '\n') g.push(s, 1);
  2091. }
  2092. else if (s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>')) // comment ends here
  2093. {
  2094. *g.flush(s) = 0;
  2095. return s + (s[2] == '>' ? 3 : 2);
  2096. }
  2097. else if (*s == 0)
  2098. {
  2099. return 0;
  2100. }
  2101. else ++s;
  2102. }
  2103. }
  2104. PUGI__FN char_t* strconv_cdata(char_t* s, char_t endch)
  2105. {
  2106. gap g;
  2107. while (true)
  2108. {
  2109. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_cdata));
  2110. if (*s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  2111. {
  2112. *s++ = '\n'; // replace first one with 0x0a
  2113. if (*s == '\n') g.push(s, 1);
  2114. }
  2115. else if (s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>')) // CDATA ends here
  2116. {
  2117. *g.flush(s) = 0;
  2118. return s + 1;
  2119. }
  2120. else if (*s == 0)
  2121. {
  2122. return 0;
  2123. }
  2124. else ++s;
  2125. }
  2126. }
  2127. typedef char_t* (*strconv_pcdata_t)(char_t*);
  2128. template <typename opt_trim, typename opt_eol, typename opt_escape> struct strconv_pcdata_impl
  2129. {
  2130. static char_t* parse(char_t* s)
  2131. {
  2132. gap g;
  2133. char_t* begin = s;
  2134. while (true)
  2135. {
  2136. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_pcdata));
  2137. if (*s == '<') // PCDATA ends here
  2138. {
  2139. char_t* end = g.flush(s);
  2140. if (opt_trim::value)
  2141. while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))
  2142. --end;
  2143. *end = 0;
  2144. return s + 1;
  2145. }
  2146. else if (opt_eol::value && *s == '\r') // Either a single 0x0d or 0x0d 0x0a pair
  2147. {
  2148. *s++ = '\n'; // replace first one with 0x0a
  2149. if (*s == '\n') g.push(s, 1);
  2150. }
  2151. else if (opt_escape::value && *s == '&')
  2152. {
  2153. s = strconv_escape(s, g);
  2154. }
  2155. else if (*s == 0)
  2156. {
  2157. char_t* end = g.flush(s);
  2158. if (opt_trim::value)
  2159. while (end > begin && PUGI__IS_CHARTYPE(end[-1], ct_space))
  2160. --end;
  2161. *end = 0;
  2162. return s;
  2163. }
  2164. else ++s;
  2165. }
  2166. }
  2167. };
  2168. PUGI__FN strconv_pcdata_t get_strconv_pcdata(unsigned int optmask)
  2169. {
  2170. PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_trim_pcdata == 0x0800);
  2171. switch (((optmask >> 4) & 3) | ((optmask >> 9) & 4)) // get bitmask for flags (trim eol escapes); this simultaneously checks 3 options from assertion above
  2172. {
  2173. case 0: return strconv_pcdata_impl<opt_false, opt_false, opt_false>::parse;
  2174. case 1: return strconv_pcdata_impl<opt_false, opt_false, opt_true>::parse;
  2175. case 2: return strconv_pcdata_impl<opt_false, opt_true, opt_false>::parse;
  2176. case 3: return strconv_pcdata_impl<opt_false, opt_true, opt_true>::parse;
  2177. case 4: return strconv_pcdata_impl<opt_true, opt_false, opt_false>::parse;
  2178. case 5: return strconv_pcdata_impl<opt_true, opt_false, opt_true>::parse;
  2179. case 6: return strconv_pcdata_impl<opt_true, opt_true, opt_false>::parse;
  2180. case 7: return strconv_pcdata_impl<opt_true, opt_true, opt_true>::parse;
  2181. default: assert(false); return 0; // unreachable
  2182. }
  2183. }
  2184. typedef char_t* (*strconv_attribute_t)(char_t*, char_t);
  2185. template <typename opt_escape> struct strconv_attribute_impl
  2186. {
  2187. static char_t* parse_wnorm(char_t* s, char_t end_quote)
  2188. {
  2189. gap g;
  2190. // trim leading whitespaces
  2191. if (PUGI__IS_CHARTYPE(*s, ct_space))
  2192. {
  2193. char_t* str = s;
  2194. do ++str;
  2195. while (PUGI__IS_CHARTYPE(*str, ct_space));
  2196. g.push(s, str - s);
  2197. }
  2198. while (true)
  2199. {
  2200. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws | ct_space));
  2201. if (*s == end_quote)
  2202. {
  2203. char_t* str = g.flush(s);
  2204. do *str-- = 0;
  2205. while (PUGI__IS_CHARTYPE(*str, ct_space));
  2206. return s + 1;
  2207. }
  2208. else if (PUGI__IS_CHARTYPE(*s, ct_space))
  2209. {
  2210. *s++ = ' ';
  2211. if (PUGI__IS_CHARTYPE(*s, ct_space))
  2212. {
  2213. char_t* str = s + 1;
  2214. while (PUGI__IS_CHARTYPE(*str, ct_space)) ++str;
  2215. g.push(s, str - s);
  2216. }
  2217. }
  2218. else if (opt_escape::value && *s == '&')
  2219. {
  2220. s = strconv_escape(s, g);
  2221. }
  2222. else if (!*s)
  2223. {
  2224. return 0;
  2225. }
  2226. else ++s;
  2227. }
  2228. }
  2229. static char_t* parse_wconv(char_t* s, char_t end_quote)
  2230. {
  2231. gap g;
  2232. while (true)
  2233. {
  2234. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr_ws));
  2235. if (*s == end_quote)
  2236. {
  2237. *g.flush(s) = 0;
  2238. return s + 1;
  2239. }
  2240. else if (PUGI__IS_CHARTYPE(*s, ct_space))
  2241. {
  2242. if (*s == '\r')
  2243. {
  2244. *s++ = ' ';
  2245. if (*s == '\n') g.push(s, 1);
  2246. }
  2247. else *s++ = ' ';
  2248. }
  2249. else if (opt_escape::value && *s == '&')
  2250. {
  2251. s = strconv_escape(s, g);
  2252. }
  2253. else if (!*s)
  2254. {
  2255. return 0;
  2256. }
  2257. else ++s;
  2258. }
  2259. }
  2260. static char_t* parse_eol(char_t* s, char_t end_quote)
  2261. {
  2262. gap g;
  2263. while (true)
  2264. {
  2265. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr));
  2266. if (*s == end_quote)
  2267. {
  2268. *g.flush(s) = 0;
  2269. return s + 1;
  2270. }
  2271. else if (*s == '\r')
  2272. {
  2273. *s++ = '\n';
  2274. if (*s == '\n') g.push(s, 1);
  2275. }
  2276. else if (opt_escape::value && *s == '&')
  2277. {
  2278. s = strconv_escape(s, g);
  2279. }
  2280. else if (!*s)
  2281. {
  2282. return 0;
  2283. }
  2284. else ++s;
  2285. }
  2286. }
  2287. static char_t* parse_simple(char_t* s, char_t end_quote)
  2288. {
  2289. gap g;
  2290. while (true)
  2291. {
  2292. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPE(ss, ct_parse_attr));
  2293. if (*s == end_quote)
  2294. {
  2295. *g.flush(s) = 0;
  2296. return s + 1;
  2297. }
  2298. else if (opt_escape::value && *s == '&')
  2299. {
  2300. s = strconv_escape(s, g);
  2301. }
  2302. else if (!*s)
  2303. {
  2304. return 0;
  2305. }
  2306. else ++s;
  2307. }
  2308. }
  2309. };
  2310. PUGI__FN strconv_attribute_t get_strconv_attribute(unsigned int optmask)
  2311. {
  2312. PUGI__STATIC_ASSERT(parse_escapes == 0x10 && parse_eol == 0x20 && parse_wconv_attribute == 0x40 && parse_wnorm_attribute == 0x80);
  2313. switch ((optmask >> 4) & 15) // get bitmask for flags (wnorm wconv eol escapes); this simultaneously checks 4 options from assertion above
  2314. {
  2315. case 0: return strconv_attribute_impl<opt_false>::parse_simple;
  2316. case 1: return strconv_attribute_impl<opt_true>::parse_simple;
  2317. case 2: return strconv_attribute_impl<opt_false>::parse_eol;
  2318. case 3: return strconv_attribute_impl<opt_true>::parse_eol;
  2319. case 4: return strconv_attribute_impl<opt_false>::parse_wconv;
  2320. case 5: return strconv_attribute_impl<opt_true>::parse_wconv;
  2321. case 6: return strconv_attribute_impl<opt_false>::parse_wconv;
  2322. case 7: return strconv_attribute_impl<opt_true>::parse_wconv;
  2323. case 8: return strconv_attribute_impl<opt_false>::parse_wnorm;
  2324. case 9: return strconv_attribute_impl<opt_true>::parse_wnorm;
  2325. case 10: return strconv_attribute_impl<opt_false>::parse_wnorm;
  2326. case 11: return strconv_attribute_impl<opt_true>::parse_wnorm;
  2327. case 12: return strconv_attribute_impl<opt_false>::parse_wnorm;
  2328. case 13: return strconv_attribute_impl<opt_true>::parse_wnorm;
  2329. case 14: return strconv_attribute_impl<opt_false>::parse_wnorm;
  2330. case 15: return strconv_attribute_impl<opt_true>::parse_wnorm;
  2331. default: assert(false); return 0; // unreachable
  2332. }
  2333. }
  2334. inline xml_parse_result make_parse_result(xml_parse_status status, ptrdiff_t offset = 0)
  2335. {
  2336. xml_parse_result result;
  2337. result.status = status;
  2338. result.offset = offset;
  2339. return result;
  2340. }
  2341. struct xml_parser
  2342. {
  2343. xml_allocator* alloc;
  2344. char_t* error_offset;
  2345. xml_parse_status error_status;
  2346. xml_parser(xml_allocator* alloc_): alloc(alloc_), error_offset(0), error_status(status_ok)
  2347. {
  2348. }
  2349. // DOCTYPE consists of nested sections of the following possible types:
  2350. // <!-- ... -->, <? ... ?>, "...", '...'
  2351. // <![...]]>
  2352. // <!...>
  2353. // First group can not contain nested groups
  2354. // Second group can contain nested groups of the same type
  2355. // Third group can contain all other groups
  2356. char_t* parse_doctype_primitive(char_t* s)
  2357. {
  2358. if (*s == '"' || *s == '\'')
  2359. {
  2360. // quoted string
  2361. char_t ch = *s++;
  2362. PUGI__SCANFOR(*s == ch);
  2363. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  2364. s++;
  2365. }
  2366. else if (s[0] == '<' && s[1] == '?')
  2367. {
  2368. // <? ... ?>
  2369. s += 2;
  2370. PUGI__SCANFOR(s[0] == '?' && s[1] == '>'); // no need for ENDSWITH because ?> can't terminate proper doctype
  2371. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  2372. s += 2;
  2373. }
  2374. else if (s[0] == '<' && s[1] == '!' && s[2] == '-' && s[3] == '-')
  2375. {
  2376. s += 4;
  2377. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && s[2] == '>'); // no need for ENDSWITH because --> can't terminate proper doctype
  2378. if (!*s) PUGI__THROW_ERROR(status_bad_doctype, s);
  2379. s += 3;
  2380. }
  2381. else PUGI__THROW_ERROR(status_bad_doctype, s);
  2382. return s;
  2383. }
  2384. char_t* parse_doctype_ignore(char_t* s)
  2385. {
  2386. size_t depth = 0;
  2387. assert(s[0] == '<' && s[1] == '!' && s[2] == '[');
  2388. s += 3;
  2389. while (*s)
  2390. {
  2391. if (s[0] == '<' && s[1] == '!' && s[2] == '[')
  2392. {
  2393. // nested ignore section
  2394. s += 3;
  2395. depth++;
  2396. }
  2397. else if (s[0] == ']' && s[1] == ']' && s[2] == '>')
  2398. {
  2399. // ignore section end
  2400. s += 3;
  2401. if (depth == 0)
  2402. return s;
  2403. depth--;
  2404. }
  2405. else s++;
  2406. }
  2407. PUGI__THROW_ERROR(status_bad_doctype, s);
  2408. }
  2409. char_t* parse_doctype_group(char_t* s, char_t endch)
  2410. {
  2411. size_t depth = 0;
  2412. assert((s[0] == '<' || s[0] == 0) && s[1] == '!');
  2413. s += 2;
  2414. while (*s)
  2415. {
  2416. if (s[0] == '<' && s[1] == '!' && s[2] != '-')
  2417. {
  2418. if (s[2] == '[')
  2419. {
  2420. // ignore
  2421. s = parse_doctype_ignore(s);
  2422. if (!s) return s;
  2423. }
  2424. else
  2425. {
  2426. // some control group
  2427. s += 2;
  2428. depth++;
  2429. }
  2430. }
  2431. else if (s[0] == '<' || s[0] == '"' || s[0] == '\'')
  2432. {
  2433. // unknown tag (forbidden), or some primitive group
  2434. s = parse_doctype_primitive(s);
  2435. if (!s) return s;
  2436. }
  2437. else if (*s == '>')
  2438. {
  2439. if (depth == 0)
  2440. return s;
  2441. depth--;
  2442. s++;
  2443. }
  2444. else s++;
  2445. }
  2446. if (depth != 0 || endch != '>') PUGI__THROW_ERROR(status_bad_doctype, s);
  2447. return s;
  2448. }
  2449. char_t* parse_exclamation(char_t* s, xml_node_struct* cursor, unsigned int optmsk, char_t endch)
  2450. {
  2451. // parse node contents, starting with exclamation mark
  2452. ++s;
  2453. if (*s == '-') // '<!-...'
  2454. {
  2455. ++s;
  2456. if (*s == '-') // '<!--...'
  2457. {
  2458. ++s;
  2459. if (PUGI__OPTSET(parse_comments))
  2460. {
  2461. PUGI__PUSHNODE(node_comment); // Append a new node on the tree.
  2462. cursor->value = s; // Save the offset.
  2463. }
  2464. if (PUGI__OPTSET(parse_eol) && PUGI__OPTSET(parse_comments))
  2465. {
  2466. s = strconv_comment(s, endch);
  2467. if (!s) PUGI__THROW_ERROR(status_bad_comment, cursor->value);
  2468. }
  2469. else
  2470. {
  2471. // Scan for terminating '-->'.
  2472. PUGI__SCANFOR(s[0] == '-' && s[1] == '-' && PUGI__ENDSWITH(s[2], '>'));
  2473. PUGI__CHECK_ERROR(status_bad_comment, s);
  2474. if (PUGI__OPTSET(parse_comments))
  2475. *s = 0; // Zero-terminate this segment at the first terminating '-'.
  2476. s += (s[2] == '>' ? 3 : 2); // Step over the '\0->'.
  2477. }
  2478. }
  2479. else PUGI__THROW_ERROR(status_bad_comment, s);
  2480. }
  2481. else if (*s == '[')
  2482. {
  2483. // '<![CDATA[...'
  2484. if (*++s=='C' && *++s=='D' && *++s=='A' && *++s=='T' && *++s=='A' && *++s == '[')
  2485. {
  2486. ++s;
  2487. if (PUGI__OPTSET(parse_cdata))
  2488. {
  2489. PUGI__PUSHNODE(node_cdata); // Append a new node on the tree.
  2490. cursor->value = s; // Save the offset.
  2491. if (PUGI__OPTSET(parse_eol))
  2492. {
  2493. s = strconv_cdata(s, endch);
  2494. if (!s) PUGI__THROW_ERROR(status_bad_cdata, cursor->value);
  2495. }
  2496. else
  2497. {
  2498. // Scan for terminating ']]>'.
  2499. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>'));
  2500. PUGI__CHECK_ERROR(status_bad_cdata, s);
  2501. *s++ = 0; // Zero-terminate this segment.
  2502. }
  2503. }
  2504. else // Flagged for discard, but we still have to scan for the terminator.
  2505. {
  2506. // Scan for terminating ']]>'.
  2507. PUGI__SCANFOR(s[0] == ']' && s[1] == ']' && PUGI__ENDSWITH(s[2], '>'));
  2508. PUGI__CHECK_ERROR(status_bad_cdata, s);
  2509. ++s;
  2510. }
  2511. s += (s[1] == '>' ? 2 : 1); // Step over the last ']>'.
  2512. }
  2513. else PUGI__THROW_ERROR(status_bad_cdata, s);
  2514. }
  2515. else if (s[0] == 'D' && s[1] == 'O' && s[2] == 'C' && s[3] == 'T' && s[4] == 'Y' && s[5] == 'P' && PUGI__ENDSWITH(s[6], 'E'))
  2516. {
  2517. s -= 2;
  2518. if (cursor->parent) PUGI__THROW_ERROR(status_bad_doctype, s);
  2519. char_t* mark = s + 9;
  2520. s = parse_doctype_group(s, endch);
  2521. if (!s) return s;
  2522. assert((*s == 0 && endch == '>') || *s == '>');
  2523. if (*s) *s++ = 0;
  2524. if (PUGI__OPTSET(parse_doctype))
  2525. {
  2526. while (PUGI__IS_CHARTYPE(*mark, ct_space)) ++mark;
  2527. PUGI__PUSHNODE(node_doctype);
  2528. cursor->value = mark;
  2529. }
  2530. }
  2531. else if (*s == 0 && endch == '-') PUGI__THROW_ERROR(status_bad_comment, s);
  2532. else if (*s == 0 && endch == '[') PUGI__THROW_ERROR(status_bad_cdata, s);
  2533. else PUGI__THROW_ERROR(status_unrecognized_tag, s);
  2534. return s;
  2535. }
  2536. char_t* parse_question(char_t* s, xml_node_struct*& ref_cursor, unsigned int optmsk, char_t endch)
  2537. {
  2538. // load into registers
  2539. xml_node_struct* cursor = ref_cursor;
  2540. char_t ch = 0;
  2541. // parse node contents, starting with question mark
  2542. ++s;
  2543. // read PI target
  2544. char_t* target = s;
  2545. if (!PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_pi, s);
  2546. PUGI__SCANWHILE(PUGI__IS_CHARTYPE(*s, ct_symbol));
  2547. PUGI__CHECK_ERROR(status_bad_pi, s);
  2548. // determine node type; stricmp / strcasecmp is not portable
  2549. bool declaration = (target[0] | ' ') == 'x' && (target[1] | ' ') == 'm' && (target[2] | ' ') == 'l' && target + 3 == s;
  2550. if (declaration ? PUGI__OPTSET(parse_declaration) : PUGI__OPTSET(parse_pi))
  2551. {
  2552. if (declaration)
  2553. {
  2554. // disallow non top-level declarations
  2555. if (cursor->parent) PUGI__THROW_ERROR(status_bad_pi, s);
  2556. PUGI__PUSHNODE(node_declaration);
  2557. }
  2558. else
  2559. {
  2560. PUGI__PUSHNODE(node_pi);
  2561. }
  2562. cursor->name = target;
  2563. PUGI__ENDSEG();
  2564. // parse value/attributes
  2565. if (ch == '?')
  2566. {
  2567. // empty node
  2568. if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_pi, s);
  2569. s += (*s == '>');
  2570. PUGI__POPNODE();
  2571. }
  2572. else if (PUGI__IS_CHARTYPE(ch, ct_space))
  2573. {
  2574. PUGI__SKIPWS();
  2575. // scan for tag end
  2576. char_t* value = s;
  2577. PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>'));
  2578. PUGI__CHECK_ERROR(status_bad_pi, s);
  2579. if (declaration)
  2580. {
  2581. // replace ending ? with / so that 'element' terminates properly
  2582. *s = '/';
  2583. // we exit from this function with cursor at node_declaration, which is a signal to parse() to go to LOC_ATTRIBUTES
  2584. s = value;
  2585. }
  2586. else
  2587. {
  2588. // store value and step over >
  2589. cursor->value = value;
  2590. PUGI__POPNODE();
  2591. PUGI__ENDSEG();
  2592. s += (*s == '>');
  2593. }
  2594. }
  2595. else PUGI__THROW_ERROR(status_bad_pi, s);
  2596. }
  2597. else
  2598. {
  2599. // scan for tag end
  2600. PUGI__SCANFOR(s[0] == '?' && PUGI__ENDSWITH(s[1], '>'));
  2601. PUGI__CHECK_ERROR(status_bad_pi, s);
  2602. s += (s[1] == '>' ? 2 : 1);
  2603. }
  2604. // store from registers
  2605. ref_cursor = cursor;
  2606. return s;
  2607. }
  2608. char_t* parse_tree(char_t* s, xml_node_struct* root, unsigned int optmsk, char_t endch)
  2609. {
  2610. strconv_attribute_t strconv_attribute = get_strconv_attribute(optmsk);
  2611. strconv_pcdata_t strconv_pcdata = get_strconv_pcdata(optmsk);
  2612. char_t ch = 0;
  2613. xml_node_struct* cursor = root;
  2614. char_t* mark = s;
  2615. while (*s != 0)
  2616. {
  2617. if (*s == '<')
  2618. {
  2619. ++s;
  2620. LOC_TAG:
  2621. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // '<#...'
  2622. {
  2623. PUGI__PUSHNODE(node_element); // Append a new node to the tree.
  2624. cursor->name = s;
  2625. PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator.
  2626. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
  2627. if (ch == '>')
  2628. {
  2629. // end of tag
  2630. }
  2631. else if (PUGI__IS_CHARTYPE(ch, ct_space))
  2632. {
  2633. LOC_ATTRIBUTES:
  2634. while (true)
  2635. {
  2636. PUGI__SKIPWS(); // Eat any whitespace.
  2637. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) // <... #...
  2638. {
  2639. xml_attribute_struct* a = append_new_attribute(cursor, *alloc); // Make space for this attribute.
  2640. if (!a) PUGI__THROW_ERROR(status_out_of_memory, s);
  2641. a->name = s; // Save the offset.
  2642. PUGI__SCANWHILE_UNROLL(PUGI__IS_CHARTYPE(ss, ct_symbol)); // Scan for a terminator.
  2643. PUGI__ENDSEG(); // Save char in 'ch', terminate & step over.
  2644. if (PUGI__IS_CHARTYPE(ch, ct_space))
  2645. {
  2646. PUGI__SKIPWS(); // Eat any whitespace.
  2647. ch = *s;
  2648. ++s;
  2649. }
  2650. if (ch == '=') // '<... #=...'
  2651. {
  2652. PUGI__SKIPWS(); // Eat any whitespace.
  2653. if (*s == '"' || *s == '\'') // '<... #="...'
  2654. {
  2655. ch = *s; // Save quote char to avoid breaking on "''" -or- '""'.
  2656. ++s; // Step over the quote.
  2657. a->value = s; // Save the offset.
  2658. s = strconv_attribute(s, ch);
  2659. if (!s) PUGI__THROW_ERROR(status_bad_attribute, a->value);
  2660. // After this line the loop continues from the start;
  2661. // Whitespaces, / and > are ok, symbols and EOF are wrong,
  2662. // everything else will be detected
  2663. if (PUGI__IS_CHARTYPE(*s, ct_start_symbol)) PUGI__THROW_ERROR(status_bad_attribute, s);
  2664. }
  2665. else PUGI__THROW_ERROR(status_bad_attribute, s);
  2666. }
  2667. else PUGI__THROW_ERROR(status_bad_attribute, s);
  2668. }
  2669. else if (*s == '/')
  2670. {
  2671. ++s;
  2672. if (*s == '>')
  2673. {
  2674. PUGI__POPNODE();
  2675. s++;
  2676. break;
  2677. }
  2678. else if (*s == 0 && endch == '>')
  2679. {
  2680. PUGI__POPNODE();
  2681. break;
  2682. }
  2683. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2684. }
  2685. else if (*s == '>')
  2686. {
  2687. ++s;
  2688. break;
  2689. }
  2690. else if (*s == 0 && endch == '>')
  2691. {
  2692. break;
  2693. }
  2694. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2695. }
  2696. // !!!
  2697. }
  2698. else if (ch == '/') // '<#.../'
  2699. {
  2700. if (!PUGI__ENDSWITH(*s, '>')) PUGI__THROW_ERROR(status_bad_start_element, s);
  2701. PUGI__POPNODE(); // Pop.
  2702. s += (*s == '>');
  2703. }
  2704. else if (ch == 0)
  2705. {
  2706. // we stepped over null terminator, backtrack & handle closing tag
  2707. --s;
  2708. if (endch != '>') PUGI__THROW_ERROR(status_bad_start_element, s);
  2709. }
  2710. else PUGI__THROW_ERROR(status_bad_start_element, s);
  2711. }
  2712. else if (*s == '/')
  2713. {
  2714. ++s;
  2715. mark = s;
  2716. char_t* name = cursor->name;
  2717. if (!name) PUGI__THROW_ERROR(status_end_element_mismatch, mark);
  2718. while (PUGI__IS_CHARTYPE(*s, ct_symbol))
  2719. {
  2720. if (*s++ != *name++) PUGI__THROW_ERROR(status_end_element_mismatch, mark);
  2721. }
  2722. if (*name)
  2723. {
  2724. if (*s == 0 && name[0] == endch && name[1] == 0) PUGI__THROW_ERROR(status_bad_end_element, s);
  2725. else PUGI__THROW_ERROR(status_end_element_mismatch, mark);
  2726. }
  2727. PUGI__POPNODE(); // Pop.
  2728. PUGI__SKIPWS();
  2729. if (*s == 0)
  2730. {
  2731. if (endch != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
  2732. }
  2733. else
  2734. {
  2735. if (*s != '>') PUGI__THROW_ERROR(status_bad_end_element, s);
  2736. ++s;
  2737. }
  2738. }
  2739. else if (*s == '?') // '<?...'
  2740. {
  2741. s = parse_question(s, cursor, optmsk, endch);
  2742. if (!s) return s;
  2743. assert(cursor);
  2744. if (PUGI__NODETYPE(cursor) == node_declaration) goto LOC_ATTRIBUTES;
  2745. }
  2746. else if (*s == '!') // '<!...'
  2747. {
  2748. s = parse_exclamation(s, cursor, optmsk, endch);
  2749. if (!s) return s;
  2750. }
  2751. else if (*s == 0 && endch == '?') PUGI__THROW_ERROR(status_bad_pi, s);
  2752. else PUGI__THROW_ERROR(status_unrecognized_tag, s);
  2753. }
  2754. else
  2755. {
  2756. mark = s; // Save this offset while searching for a terminator.
  2757. PUGI__SKIPWS(); // Eat whitespace if no genuine PCDATA here.
  2758. if (*s == '<' || !*s)
  2759. {
  2760. // We skipped some whitespace characters because otherwise we would take the tag branch instead of PCDATA one
  2761. assert(mark != s);
  2762. if (!PUGI__OPTSET(parse_ws_pcdata | parse_ws_pcdata_single) || PUGI__OPTSET(parse_trim_pcdata))
  2763. {
  2764. continue;
  2765. }
  2766. else if (PUGI__OPTSET(parse_ws_pcdata_single))
  2767. {
  2768. if (s[0] != '<' || s[1] != '/' || cursor->first_child) continue;
  2769. }
  2770. }
  2771. if (!PUGI__OPTSET(parse_trim_pcdata))
  2772. s = mark;
  2773. if (cursor->parent || PUGI__OPTSET(parse_fragment))
  2774. {
  2775. if (PUGI__OPTSET(parse_embed_pcdata) && cursor->parent && !cursor->first_child && !cursor->value)
  2776. {
  2777. cursor->value = s; // Save the offset.
  2778. }
  2779. else
  2780. {
  2781. PUGI__PUSHNODE(node_pcdata); // Append a new node on the tree.
  2782. cursor->value = s; // Save the offset.
  2783. PUGI__POPNODE(); // Pop since this is a standalone.
  2784. }
  2785. s = strconv_pcdata(s);
  2786. if (!*s) break;
  2787. }
  2788. else
  2789. {
  2790. PUGI__SCANFOR(*s == '<'); // '...<'
  2791. if (!*s) break;
  2792. ++s;
  2793. }
  2794. // We're after '<'
  2795. goto LOC_TAG;
  2796. }
  2797. }
  2798. // check that last tag is closed
  2799. if (cursor != root) PUGI__THROW_ERROR(status_end_element_mismatch, s);
  2800. return s;
  2801. }
  2802. #ifdef PUGIXML_WCHAR_MODE
  2803. static char_t* parse_skip_bom(char_t* s)
  2804. {
  2805. unsigned int bom = 0xfeff;
  2806. return (s[0] == static_cast<wchar_t>(bom)) ? s + 1 : s;
  2807. }
  2808. #else
  2809. static char_t* parse_skip_bom(char_t* s)
  2810. {
  2811. return (s[0] == '\xef' && s[1] == '\xbb' && s[2] == '\xbf') ? s + 3 : s;
  2812. }
  2813. #endif
  2814. static bool has_element_node_siblings(xml_node_struct* node)
  2815. {
  2816. while (node)
  2817. {
  2818. if (PUGI__NODETYPE(node) == node_element) return true;
  2819. node = node->next_sibling;
  2820. }
  2821. return false;
  2822. }
  2823. static xml_parse_result parse(char_t* buffer, size_t length, xml_document_struct* xmldoc, xml_node_struct* root, unsigned int optmsk)
  2824. {
  2825. // early-out for empty documents
  2826. if (length == 0)
  2827. return make_parse_result(PUGI__OPTSET(parse_fragment) ? status_ok : status_no_document_element);
  2828. // get last child of the root before parsing
  2829. xml_node_struct* last_root_child = root->first_child ? root->first_child->prev_sibling_c + 0 : 0;
  2830. // create parser on stack
  2831. xml_parser parser(static_cast<xml_allocator*>(xmldoc));
  2832. // save last character and make buffer zero-terminated (speeds up parsing)
  2833. char_t endch = buffer[length - 1];
  2834. buffer[length - 1] = 0;
  2835. // skip BOM to make sure it does not end up as part of parse output
  2836. char_t* buffer_data = parse_skip_bom(buffer);
  2837. // perform actual parsing
  2838. parser.parse_tree(buffer_data, root, optmsk, endch);
  2839. xml_parse_result result = make_parse_result(parser.error_status, parser.error_offset ? parser.error_offset - buffer : 0);
  2840. assert(result.offset >= 0 && static_cast<size_t>(result.offset) <= length);
  2841. if (result)
  2842. {
  2843. // since we removed last character, we have to handle the only possible false positive (stray <)
  2844. if (endch == '<')
  2845. return make_parse_result(status_unrecognized_tag, length - 1);
  2846. // check if there are any element nodes parsed
  2847. xml_node_struct* first_root_child_parsed = last_root_child ? last_root_child->next_sibling + 0 : root->first_child+ 0;
  2848. if (!PUGI__OPTSET(parse_fragment) && !has_element_node_siblings(first_root_child_parsed))
  2849. return make_parse_result(status_no_document_element, length - 1);
  2850. }
  2851. else
  2852. {
  2853. // roll back offset if it occurs on a null terminator in the source buffer
  2854. if (result.offset > 0 && static_cast<size_t>(result.offset) == length - 1 && endch == 0)
  2855. result.offset--;
  2856. }
  2857. return result;
  2858. }
  2859. };
  2860. // Output facilities
  2861. PUGI__FN xml_encoding get_write_native_encoding()
  2862. {
  2863. #ifdef PUGIXML_WCHAR_MODE
  2864. return get_wchar_encoding();
  2865. #else
  2866. return encoding_utf8;
  2867. #endif
  2868. }
  2869. PUGI__FN xml_encoding get_write_encoding(xml_encoding encoding)
  2870. {
  2871. // replace wchar encoding with utf implementation
  2872. if (encoding == encoding_wchar) return get_wchar_encoding();
  2873. // replace utf16 encoding with utf16 with specific endianness
  2874. if (encoding == encoding_utf16) return is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2875. // replace utf32 encoding with utf32 with specific endianness
  2876. if (encoding == encoding_utf32) return is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2877. // only do autodetection if no explicit encoding is requested
  2878. if (encoding != encoding_auto) return encoding;
  2879. // assume utf8 encoding
  2880. return encoding_utf8;
  2881. }
  2882. template <typename D, typename T> PUGI__FN size_t convert_buffer_output_generic(typename T::value_type dest, const char_t* data, size_t length, D, T)
  2883. {
  2884. PUGI__STATIC_ASSERT(sizeof(char_t) == sizeof(typename D::type));
  2885. typename T::value_type end = D::process(reinterpret_cast<const typename D::type*>(data), length, dest, T());
  2886. return static_cast<size_t>(end - dest) * sizeof(*dest);
  2887. }
  2888. template <typename D, typename T> PUGI__FN size_t convert_buffer_output_generic(typename T::value_type dest, const char_t* data, size_t length, D, T, bool opt_swap)
  2889. {
  2890. PUGI__STATIC_ASSERT(sizeof(char_t) == sizeof(typename D::type));
  2891. typename T::value_type end = D::process(reinterpret_cast<const typename D::type*>(data), length, dest, T());
  2892. if (opt_swap)
  2893. {
  2894. for (typename T::value_type i = dest; i != end; ++i)
  2895. *i = endian_swap(*i);
  2896. }
  2897. return static_cast<size_t>(end - dest) * sizeof(*dest);
  2898. }
  2899. #ifdef PUGIXML_WCHAR_MODE
  2900. PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
  2901. {
  2902. if (length < 1) return 0;
  2903. // discard last character if it's the lead of a surrogate pair
  2904. return (sizeof(wchar_t) == 2 && static_cast<unsigned int>(static_cast<uint16_t>(data[length - 1]) - 0xD800) < 0x400) ? length - 1 : length;
  2905. }
  2906. PUGI__FN size_t convert_buffer_output(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)
  2907. {
  2908. // only endian-swapping is required
  2909. if (need_endian_swap_utf(encoding, get_wchar_encoding()))
  2910. {
  2911. convert_wchar_endian_swap(r_char, data, length);
  2912. return length * sizeof(char_t);
  2913. }
  2914. // convert to utf8
  2915. if (encoding == encoding_utf8)
  2916. return convert_buffer_output_generic(r_u8, data, length, wchar_decoder(), utf8_writer());
  2917. // convert to utf16
  2918. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  2919. {
  2920. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2921. return convert_buffer_output_generic(r_u16, data, length, wchar_decoder(), utf16_writer(), native_encoding != encoding);
  2922. }
  2923. // convert to utf32
  2924. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  2925. {
  2926. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2927. return convert_buffer_output_generic(r_u32, data, length, wchar_decoder(), utf32_writer(), native_encoding != encoding);
  2928. }
  2929. // convert to latin1
  2930. if (encoding == encoding_latin1)
  2931. return convert_buffer_output_generic(r_u8, data, length, wchar_decoder(), latin1_writer());
  2932. assert(false && "Invalid encoding"); // unreachable
  2933. return 0;
  2934. }
  2935. #else
  2936. PUGI__FN size_t get_valid_length(const char_t* data, size_t length)
  2937. {
  2938. if (length < 5) return 0;
  2939. for (size_t i = 1; i <= 4; ++i)
  2940. {
  2941. uint8_t ch = static_cast<uint8_t>(data[length - i]);
  2942. // either a standalone character or a leading one
  2943. if ((ch & 0xc0) != 0x80) return length - i;
  2944. }
  2945. // there are four non-leading characters at the end, sequence tail is broken so might as well process the whole chunk
  2946. return length;
  2947. }
  2948. PUGI__FN size_t convert_buffer_output(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)
  2949. {
  2950. if (encoding == encoding_utf16_be || encoding == encoding_utf16_le)
  2951. {
  2952. xml_encoding native_encoding = is_little_endian() ? encoding_utf16_le : encoding_utf16_be;
  2953. return convert_buffer_output_generic(r_u16, data, length, utf8_decoder(), utf16_writer(), native_encoding != encoding);
  2954. }
  2955. if (encoding == encoding_utf32_be || encoding == encoding_utf32_le)
  2956. {
  2957. xml_encoding native_encoding = is_little_endian() ? encoding_utf32_le : encoding_utf32_be;
  2958. return convert_buffer_output_generic(r_u32, data, length, utf8_decoder(), utf32_writer(), native_encoding != encoding);
  2959. }
  2960. if (encoding == encoding_latin1)
  2961. return convert_buffer_output_generic(r_u8, data, length, utf8_decoder(), latin1_writer());
  2962. assert(false && "Invalid encoding"); // unreachable
  2963. return 0;
  2964. }
  2965. #endif
  2966. class xml_buffered_writer
  2967. {
  2968. xml_buffered_writer(const xml_buffered_writer&);
  2969. xml_buffered_writer& operator=(const xml_buffered_writer&);
  2970. public:
  2971. xml_buffered_writer(xml_writer& writer_, xml_encoding user_encoding): writer(writer_), bufsize(0), encoding(get_write_encoding(user_encoding))
  2972. {
  2973. PUGI__STATIC_ASSERT(bufcapacity >= 8);
  2974. }
  2975. size_t flush()
  2976. {
  2977. flush(buffer, bufsize);
  2978. bufsize = 0;
  2979. return 0;
  2980. }
  2981. void flush(const char_t* data, size_t size)
  2982. {
  2983. if (size == 0) return;
  2984. // fast path, just write data
  2985. if (encoding == get_write_native_encoding())
  2986. writer.write(data, size * sizeof(char_t));
  2987. else
  2988. {
  2989. // convert chunk
  2990. size_t result = convert_buffer_output(scratch.data_char, scratch.data_u8, scratch.data_u16, scratch.data_u32, data, size, encoding);
  2991. assert(result <= sizeof(scratch));
  2992. // write data
  2993. writer.write(scratch.data_u8, result);
  2994. }
  2995. }
  2996. void write_direct(const char_t* data, size_t length)
  2997. {
  2998. // flush the remaining buffer contents
  2999. flush();
  3000. // handle large chunks
  3001. if (length > bufcapacity)
  3002. {
  3003. if (encoding == get_write_native_encoding())
  3004. {
  3005. // fast path, can just write data chunk
  3006. writer.write(data, length * sizeof(char_t));
  3007. return;
  3008. }
  3009. // need to convert in suitable chunks
  3010. while (length > bufcapacity)
  3011. {
  3012. // get chunk size by selecting such number of characters that are guaranteed to fit into scratch buffer
  3013. // and form a complete codepoint sequence (i.e. discard start of last codepoint if necessary)
  3014. size_t chunk_size = get_valid_length(data, bufcapacity);
  3015. assert(chunk_size);
  3016. // convert chunk and write
  3017. flush(data, chunk_size);
  3018. // iterate
  3019. data += chunk_size;
  3020. length -= chunk_size;
  3021. }
  3022. // small tail is copied below
  3023. bufsize = 0;
  3024. }
  3025. memcpy(buffer + bufsize, data, length * sizeof(char_t));
  3026. bufsize += length;
  3027. }
  3028. void write_buffer(const char_t* data, size_t length)
  3029. {
  3030. size_t offset = bufsize;
  3031. if (offset + length <= bufcapacity)
  3032. {
  3033. memcpy(buffer + offset, data, length * sizeof(char_t));
  3034. bufsize = offset + length;
  3035. }
  3036. else
  3037. {
  3038. write_direct(data, length);
  3039. }
  3040. }
  3041. void write_string(const char_t* data)
  3042. {
  3043. // write the part of the string that fits in the buffer
  3044. size_t offset = bufsize;
  3045. while (*data && offset < bufcapacity)
  3046. buffer[offset++] = *data++;
  3047. // write the rest
  3048. if (offset < bufcapacity)
  3049. {
  3050. bufsize = offset;
  3051. }
  3052. else
  3053. {
  3054. // backtrack a bit if we have split the codepoint
  3055. size_t length = offset - bufsize;
  3056. size_t extra = length - get_valid_length(data - length, length);
  3057. bufsize = offset - extra;
  3058. write_direct(data - extra, strlength(data) + extra);
  3059. }
  3060. }
  3061. void write(char_t d0)
  3062. {
  3063. size_t offset = bufsize;
  3064. if (offset > bufcapacity - 1) offset = flush();
  3065. buffer[offset + 0] = d0;
  3066. bufsize = offset + 1;
  3067. }
  3068. void write(char_t d0, char_t d1)
  3069. {
  3070. size_t offset = bufsize;
  3071. if (offset > bufcapacity - 2) offset = flush();
  3072. buffer[offset + 0] = d0;
  3073. buffer[offset + 1] = d1;
  3074. bufsize = offset + 2;
  3075. }
  3076. void write(char_t d0, char_t d1, char_t d2)
  3077. {
  3078. size_t offset = bufsize;
  3079. if (offset > bufcapacity - 3) offset = flush();
  3080. buffer[offset + 0] = d0;
  3081. buffer[offset + 1] = d1;
  3082. buffer[offset + 2] = d2;
  3083. bufsize = offset + 3;
  3084. }
  3085. void write(char_t d0, char_t d1, char_t d2, char_t d3)
  3086. {
  3087. size_t offset = bufsize;
  3088. if (offset > bufcapacity - 4) offset = flush();
  3089. buffer[offset + 0] = d0;
  3090. buffer[offset + 1] = d1;
  3091. buffer[offset + 2] = d2;
  3092. buffer[offset + 3] = d3;
  3093. bufsize = offset + 4;
  3094. }
  3095. void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4)
  3096. {
  3097. size_t offset = bufsize;
  3098. if (offset > bufcapacity - 5) offset = flush();
  3099. buffer[offset + 0] = d0;
  3100. buffer[offset + 1] = d1;
  3101. buffer[offset + 2] = d2;
  3102. buffer[offset + 3] = d3;
  3103. buffer[offset + 4] = d4;
  3104. bufsize = offset + 5;
  3105. }
  3106. void write(char_t d0, char_t d1, char_t d2, char_t d3, char_t d4, char_t d5)
  3107. {
  3108. size_t offset = bufsize;
  3109. if (offset > bufcapacity - 6) offset = flush();
  3110. buffer[offset + 0] = d0;
  3111. buffer[offset + 1] = d1;
  3112. buffer[offset + 2] = d2;
  3113. buffer[offset + 3] = d3;
  3114. buffer[offset + 4] = d4;
  3115. buffer[offset + 5] = d5;
  3116. bufsize = offset + 6;
  3117. }
  3118. // utf8 maximum expansion: x4 (-> utf32)
  3119. // utf16 maximum expansion: x2 (-> utf32)
  3120. // utf32 maximum expansion: x1
  3121. enum
  3122. {
  3123. bufcapacitybytes =
  3124. #ifdef PUGIXML_MEMORY_OUTPUT_STACK
  3125. PUGIXML_MEMORY_OUTPUT_STACK
  3126. #else
  3127. 10240
  3128. #endif
  3129. ,
  3130. bufcapacity = bufcapacitybytes / (sizeof(char_t) + 4)
  3131. };
  3132. char_t buffer[bufcapacity];
  3133. union
  3134. {
  3135. uint8_t data_u8[4 * bufcapacity];
  3136. uint16_t data_u16[2 * bufcapacity];
  3137. uint32_t data_u32[bufcapacity];
  3138. char_t data_char[bufcapacity];
  3139. } scratch;
  3140. xml_writer& writer;
  3141. size_t bufsize;
  3142. xml_encoding encoding;
  3143. };
  3144. PUGI__FN void text_output_escaped(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
  3145. {
  3146. while (*s)
  3147. {
  3148. const char_t* prev = s;
  3149. // While *s is a usual symbol
  3150. PUGI__SCANWHILE_UNROLL(!PUGI__IS_CHARTYPEX(ss, type));
  3151. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  3152. switch (*s)
  3153. {
  3154. case 0: break;
  3155. case '&':
  3156. writer.write('&', 'a', 'm', 'p', ';');
  3157. ++s;
  3158. break;
  3159. case '<':
  3160. writer.write('&', 'l', 't', ';');
  3161. ++s;
  3162. break;
  3163. case '>':
  3164. writer.write('&', 'g', 't', ';');
  3165. ++s;
  3166. break;
  3167. case '"':
  3168. if (flags & format_attribute_single_quote)
  3169. writer.write('"');
  3170. else
  3171. writer.write('&', 'q', 'u', 'o', 't', ';');
  3172. ++s;
  3173. break;
  3174. case '\'':
  3175. if (flags & format_attribute_single_quote)
  3176. writer.write('&', 'a', 'p', 'o', 's', ';');
  3177. else
  3178. writer.write('\'');
  3179. ++s;
  3180. break;
  3181. default: // s is not a usual symbol
  3182. {
  3183. unsigned int ch = static_cast<unsigned int>(*s++);
  3184. assert(ch < 32);
  3185. if (!(flags & format_skip_control_chars))
  3186. writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';');
  3187. }
  3188. }
  3189. }
  3190. }
  3191. PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
  3192. {
  3193. if (flags & format_no_escapes)
  3194. writer.write_string(s);
  3195. else
  3196. text_output_escaped(writer, s, type, flags);
  3197. }
  3198. PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s)
  3199. {
  3200. do
  3201. {
  3202. writer.write('<', '!', '[', 'C', 'D');
  3203. writer.write('A', 'T', 'A', '[');
  3204. const char_t* prev = s;
  3205. // look for ]]> sequence - we can't output it as is since it terminates CDATA
  3206. while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s;
  3207. // skip ]] if we stopped at ]]>, > will go to the next CDATA section
  3208. if (*s) s += 2;
  3209. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  3210. writer.write(']', ']', '>');
  3211. }
  3212. while (*s);
  3213. }
  3214. PUGI__FN void text_output_indent(xml_buffered_writer& writer, const char_t* indent, size_t indent_length, unsigned int depth)
  3215. {
  3216. switch (indent_length)
  3217. {
  3218. case 1:
  3219. {
  3220. for (unsigned int i = 0; i < depth; ++i)
  3221. writer.write(indent[0]);
  3222. break;
  3223. }
  3224. case 2:
  3225. {
  3226. for (unsigned int i = 0; i < depth; ++i)
  3227. writer.write(indent[0], indent[1]);
  3228. break;
  3229. }
  3230. case 3:
  3231. {
  3232. for (unsigned int i = 0; i < depth; ++i)
  3233. writer.write(indent[0], indent[1], indent[2]);
  3234. break;
  3235. }
  3236. case 4:
  3237. {
  3238. for (unsigned int i = 0; i < depth; ++i)
  3239. writer.write(indent[0], indent[1], indent[2], indent[3]);
  3240. break;
  3241. }
  3242. default:
  3243. {
  3244. for (unsigned int i = 0; i < depth; ++i)
  3245. writer.write_buffer(indent, indent_length);
  3246. }
  3247. }
  3248. }
  3249. PUGI__FN void node_output_comment(xml_buffered_writer& writer, const char_t* s)
  3250. {
  3251. writer.write('<', '!', '-', '-');
  3252. while (*s)
  3253. {
  3254. const char_t* prev = s;
  3255. // look for -\0 or -- sequence - we can't output it since -- is illegal in comment body
  3256. while (*s && !(s[0] == '-' && (s[1] == '-' || s[1] == 0))) ++s;
  3257. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  3258. if (*s)
  3259. {
  3260. assert(*s == '-');
  3261. writer.write('-', ' ');
  3262. ++s;
  3263. }
  3264. }
  3265. writer.write('-', '-', '>');
  3266. }
  3267. PUGI__FN void node_output_pi_value(xml_buffered_writer& writer, const char_t* s)
  3268. {
  3269. while (*s)
  3270. {
  3271. const char_t* prev = s;
  3272. // look for ?> sequence - we can't output it since ?> terminates PI
  3273. while (*s && !(s[0] == '?' && s[1] == '>')) ++s;
  3274. writer.write_buffer(prev, static_cast<size_t>(s - prev));
  3275. if (*s)
  3276. {
  3277. assert(s[0] == '?' && s[1] == '>');
  3278. writer.write('?', ' ', '>');
  3279. s += 2;
  3280. }
  3281. }
  3282. }
  3283. PUGI__FN void node_output_attributes(xml_buffered_writer& writer, xml_node_struct* node, const char_t* indent, size_t indent_length, unsigned int flags, unsigned int depth)
  3284. {
  3285. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  3286. const char_t enquotation_char = (flags & format_attribute_single_quote) ? '\'' : '"';
  3287. for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute)
  3288. {
  3289. if ((flags & (format_indent_attributes | format_raw)) == format_indent_attributes)
  3290. {
  3291. writer.write('\n');
  3292. text_output_indent(writer, indent, indent_length, depth + 1);
  3293. }
  3294. else
  3295. {
  3296. writer.write(' ');
  3297. }
  3298. writer.write_string(a->name ? a->name + 0 : default_name);
  3299. writer.write('=', enquotation_char);
  3300. if (a->value)
  3301. text_output(writer, a->value, ctx_special_attr, flags);
  3302. writer.write(enquotation_char);
  3303. }
  3304. }
  3305. PUGI__FN bool node_output_start(xml_buffered_writer& writer, xml_node_struct* node, const char_t* indent, size_t indent_length, unsigned int flags, unsigned int depth)
  3306. {
  3307. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  3308. const char_t* name = node->name ? node->name + 0 : default_name;
  3309. writer.write('<');
  3310. writer.write_string(name);
  3311. if (node->first_attribute)
  3312. node_output_attributes(writer, node, indent, indent_length, flags, depth);
  3313. // element nodes can have value if parse_embed_pcdata was used
  3314. if (!node->value)
  3315. {
  3316. if (!node->first_child)
  3317. {
  3318. if (flags & format_no_empty_element_tags)
  3319. {
  3320. writer.write('>', '<', '/');
  3321. writer.write_string(name);
  3322. writer.write('>');
  3323. return false;
  3324. }
  3325. else
  3326. {
  3327. if ((flags & format_raw) == 0)
  3328. writer.write(' ');
  3329. writer.write('/', '>');
  3330. return false;
  3331. }
  3332. }
  3333. else
  3334. {
  3335. writer.write('>');
  3336. return true;
  3337. }
  3338. }
  3339. else
  3340. {
  3341. writer.write('>');
  3342. text_output(writer, node->value, ctx_special_pcdata, flags);
  3343. if (!node->first_child)
  3344. {
  3345. writer.write('<', '/');
  3346. writer.write_string(name);
  3347. writer.write('>');
  3348. return false;
  3349. }
  3350. else
  3351. {
  3352. return true;
  3353. }
  3354. }
  3355. }
  3356. PUGI__FN void node_output_end(xml_buffered_writer& writer, xml_node_struct* node)
  3357. {
  3358. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  3359. const char_t* name = node->name ? node->name + 0 : default_name;
  3360. writer.write('<', '/');
  3361. writer.write_string(name);
  3362. writer.write('>');
  3363. }
  3364. PUGI__FN void node_output_simple(xml_buffered_writer& writer, xml_node_struct* node, unsigned int flags)
  3365. {
  3366. const char_t* default_name = PUGIXML_TEXT(":anonymous");
  3367. switch (PUGI__NODETYPE(node))
  3368. {
  3369. case node_pcdata:
  3370. text_output(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""), ctx_special_pcdata, flags);
  3371. break;
  3372. case node_cdata:
  3373. text_output_cdata(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""));
  3374. break;
  3375. case node_comment:
  3376. node_output_comment(writer, node->value ? node->value + 0 : PUGIXML_TEXT(""));
  3377. break;
  3378. case node_pi:
  3379. writer.write('<', '?');
  3380. writer.write_string(node->name ? node->name + 0 : default_name);
  3381. if (node->value)
  3382. {
  3383. writer.write(' ');
  3384. node_output_pi_value(writer, node->value);
  3385. }
  3386. writer.write('?', '>');
  3387. break;
  3388. case node_declaration:
  3389. writer.write('<', '?');
  3390. writer.write_string(node->name ? node->name + 0 : default_name);
  3391. node_output_attributes(writer, node, PUGIXML_TEXT(""), 0, flags | format_raw, 0);
  3392. writer.write('?', '>');
  3393. break;
  3394. case node_doctype:
  3395. writer.write('<', '!', 'D', 'O', 'C');
  3396. writer.write('T', 'Y', 'P', 'E');
  3397. if (node->value)
  3398. {
  3399. writer.write(' ');
  3400. writer.write_string(node->value);
  3401. }
  3402. writer.write('>');
  3403. break;
  3404. default:
  3405. assert(false && "Invalid node type"); // unreachable
  3406. }
  3407. }
  3408. enum indent_flags_t
  3409. {
  3410. indent_newline = 1,
  3411. indent_indent = 2
  3412. };
  3413. PUGI__FN void node_output(xml_buffered_writer& writer, xml_node_struct* root, const char_t* indent, unsigned int flags, unsigned int depth)
  3414. {
  3415. size_t indent_length = ((flags & (format_indent | format_indent_attributes)) && (flags & format_raw) == 0) ? strlength(indent) : 0;
  3416. unsigned int indent_flags = indent_indent;
  3417. xml_node_struct* node = root;
  3418. do
  3419. {
  3420. assert(node);
  3421. // begin writing current node
  3422. if (PUGI__NODETYPE(node) == node_pcdata || PUGI__NODETYPE(node) == node_cdata)
  3423. {
  3424. node_output_simple(writer, node, flags);
  3425. indent_flags = 0;
  3426. }
  3427. else
  3428. {
  3429. if ((indent_flags & indent_newline) && (flags & format_raw) == 0)
  3430. writer.write('\n');
  3431. if ((indent_flags & indent_indent) && indent_length)
  3432. text_output_indent(writer, indent, indent_length, depth);
  3433. if (PUGI__NODETYPE(node) == node_element)
  3434. {
  3435. indent_flags = indent_newline | indent_indent;
  3436. if (node_output_start(writer, node, indent, indent_length, flags, depth))
  3437. {
  3438. // element nodes can have value if parse_embed_pcdata was used
  3439. if (node->value)
  3440. indent_flags = 0;
  3441. node = node->first_child;
  3442. depth++;
  3443. continue;
  3444. }
  3445. }
  3446. else if (PUGI__NODETYPE(node) == node_document)
  3447. {
  3448. indent_flags = indent_indent;
  3449. if (node->first_child)
  3450. {
  3451. node = node->first_child;
  3452. continue;
  3453. }
  3454. }
  3455. else
  3456. {
  3457. node_output_simple(writer, node, flags);
  3458. indent_flags = indent_newline | indent_indent;
  3459. }
  3460. }
  3461. // continue to the next node
  3462. while (node != root)
  3463. {
  3464. if (node->next_sibling)
  3465. {
  3466. node = node->next_sibling;
  3467. break;
  3468. }
  3469. node = node->parent;
  3470. // write closing node
  3471. if (PUGI__NODETYPE(node) == node_element)
  3472. {
  3473. depth--;
  3474. if ((indent_flags & indent_newline) && (flags & format_raw) == 0)
  3475. writer.write('\n');
  3476. if ((indent_flags & indent_indent) && indent_length)
  3477. text_output_indent(writer, indent, indent_length, depth);
  3478. node_output_end(writer, node);
  3479. indent_flags = indent_newline | indent_indent;
  3480. }
  3481. }
  3482. }
  3483. while (node != root);
  3484. if ((indent_flags & indent_newline) && (flags & format_raw) == 0)
  3485. writer.write('\n');
  3486. }
  3487. PUGI__FN bool has_declaration(xml_node_struct* node)
  3488. {
  3489. for (xml_node_struct* child = node->first_child; child; child = child->next_sibling)
  3490. {
  3491. xml_node_type type = PUGI__NODETYPE(child);
  3492. if (type == node_declaration) return true;
  3493. if (type == node_element) return false;
  3494. }
  3495. return false;
  3496. }
  3497. PUGI__FN bool is_attribute_of(xml_attribute_struct* attr, xml_node_struct* node)
  3498. {
  3499. for (xml_attribute_struct* a = node->first_attribute; a; a = a->next_attribute)
  3500. if (a == attr)
  3501. return true;
  3502. return false;
  3503. }
  3504. PUGI__FN bool allow_insert_attribute(xml_node_type parent)
  3505. {
  3506. return parent == node_element || parent == node_declaration;
  3507. }
  3508. PUGI__FN bool allow_insert_child(xml_node_type parent, xml_node_type child)
  3509. {
  3510. if (parent != node_document && parent != node_element) return false;
  3511. if (child == node_document || child == node_null) return false;
  3512. if (parent != node_document && (child == node_declaration || child == node_doctype)) return false;
  3513. return true;
  3514. }
  3515. PUGI__FN bool allow_move(xml_node parent, xml_node child)
  3516. {
  3517. // check that child can be a child of parent
  3518. if (!allow_insert_child(parent.type(), child.type()))
  3519. return false;
  3520. // check that node is not moved between documents
  3521. if (parent.root() != child.root())
  3522. return false;
  3523. // check that new parent is not in the child subtree
  3524. xml_node cur = parent;
  3525. while (cur)
  3526. {
  3527. if (cur == child)
  3528. return false;
  3529. cur = cur.parent();
  3530. }
  3531. return true;
  3532. }
  3533. template <typename String, typename Header>
  3534. PUGI__FN void node_copy_string(String& dest, Header& header, uintptr_t header_mask, char_t* source, Header& source_header, xml_allocator* alloc)
  3535. {
  3536. assert(!dest && (header & header_mask) == 0);
  3537. if (source)
  3538. {
  3539. if (alloc && (source_header & header_mask) == 0)
  3540. {
  3541. dest = source;
  3542. // since strcpy_insitu can reuse document buffer memory we need to mark both source and dest as shared
  3543. header |= xml_memory_page_contents_shared_mask;
  3544. source_header |= xml_memory_page_contents_shared_mask;
  3545. }
  3546. else
  3547. strcpy_insitu(dest, header, header_mask, source, strlength(source));
  3548. }
  3549. }
  3550. PUGI__FN void node_copy_contents(xml_node_struct* dn, xml_node_struct* sn, xml_allocator* shared_alloc)
  3551. {
  3552. node_copy_string(dn->name, dn->header, xml_memory_page_name_allocated_mask, sn->name, sn->header, shared_alloc);
  3553. node_copy_string(dn->value, dn->header, xml_memory_page_value_allocated_mask, sn->value, sn->header, shared_alloc);
  3554. for (xml_attribute_struct* sa = sn->first_attribute; sa; sa = sa->next_attribute)
  3555. {
  3556. xml_attribute_struct* da = append_new_attribute(dn, get_allocator(dn));
  3557. if (da)
  3558. {
  3559. node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc);
  3560. node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc);
  3561. }
  3562. }
  3563. }
  3564. PUGI__FN void node_copy_tree(xml_node_struct* dn, xml_node_struct* sn)
  3565. {
  3566. xml_allocator& alloc = get_allocator(dn);
  3567. xml_allocator* shared_alloc = (&alloc == &get_allocator(sn)) ? &alloc : 0;
  3568. node_copy_contents(dn, sn, shared_alloc);
  3569. xml_node_struct* dit = dn;
  3570. xml_node_struct* sit = sn->first_child;
  3571. while (sit && sit != sn)
  3572. {
  3573. // when a tree is copied into one of the descendants, we need to skip that subtree to avoid an infinite loop
  3574. if (sit != dn)
  3575. {
  3576. xml_node_struct* copy = append_new_node(dit, alloc, PUGI__NODETYPE(sit));
  3577. if (copy)
  3578. {
  3579. node_copy_contents(copy, sit, shared_alloc);
  3580. if (sit->first_child)
  3581. {
  3582. dit = copy;
  3583. sit = sit->first_child;
  3584. continue;
  3585. }
  3586. }
  3587. }
  3588. // continue to the next node
  3589. do
  3590. {
  3591. if (sit->next_sibling)
  3592. {
  3593. sit = sit->next_sibling;
  3594. break;
  3595. }
  3596. sit = sit->parent;
  3597. dit = dit->parent;
  3598. }
  3599. while (sit != sn);
  3600. }
  3601. }
  3602. PUGI__FN void node_copy_attribute(xml_attribute_struct* da, xml_attribute_struct* sa)
  3603. {
  3604. xml_allocator& alloc = get_allocator(da);
  3605. xml_allocator* shared_alloc = (&alloc == &get_allocator(sa)) ? &alloc : 0;
  3606. node_copy_string(da->name, da->header, xml_memory_page_name_allocated_mask, sa->name, sa->header, shared_alloc);
  3607. node_copy_string(da->value, da->header, xml_memory_page_value_allocated_mask, sa->value, sa->header, shared_alloc);
  3608. }
  3609. inline bool is_text_node(xml_node_struct* node)
  3610. {
  3611. xml_node_type type = PUGI__NODETYPE(node);
  3612. return type == node_pcdata || type == node_cdata;
  3613. }
  3614. // get value with conversion functions
  3615. template <typename U> PUGI__FN PUGI__UNSIGNED_OVERFLOW U string_to_integer(const char_t* value, U minv, U maxv)
  3616. {
  3617. U result = 0;
  3618. const char_t* s = value;
  3619. while (PUGI__IS_CHARTYPE(*s, ct_space))
  3620. s++;
  3621. bool negative = (*s == '-');
  3622. s += (*s == '+' || *s == '-');
  3623. bool overflow = false;
  3624. if (s[0] == '0' && (s[1] | ' ') == 'x')
  3625. {
  3626. s += 2;
  3627. // since overflow detection relies on length of the sequence skip leading zeros
  3628. while (*s == '0')
  3629. s++;
  3630. const char_t* start = s;
  3631. for (;;)
  3632. {
  3633. if (static_cast<unsigned>(*s - '0') < 10)
  3634. result = result * 16 + (*s - '0');
  3635. else if (static_cast<unsigned>((*s | ' ') - 'a') < 6)
  3636. result = result * 16 + ((*s | ' ') - 'a' + 10);
  3637. else
  3638. break;
  3639. s++;
  3640. }
  3641. size_t digits = static_cast<size_t>(s - start);
  3642. overflow = digits > sizeof(U) * 2;
  3643. }
  3644. else
  3645. {
  3646. // since overflow detection relies on length of the sequence skip leading zeros
  3647. while (*s == '0')
  3648. s++;
  3649. const char_t* start = s;
  3650. for (;;)
  3651. {
  3652. if (static_cast<unsigned>(*s - '0') < 10)
  3653. result = result * 10 + (*s - '0');
  3654. else
  3655. break;
  3656. s++;
  3657. }
  3658. size_t digits = static_cast<size_t>(s - start);
  3659. PUGI__STATIC_ASSERT(sizeof(U) == 8 || sizeof(U) == 4 || sizeof(U) == 2);
  3660. const size_t max_digits10 = sizeof(U) == 8 ? 20 : sizeof(U) == 4 ? 10 : 5;
  3661. const char_t max_lead = sizeof(U) == 8 ? '1' : sizeof(U) == 4 ? '4' : '6';
  3662. const size_t high_bit = sizeof(U) * 8 - 1;
  3663. overflow = digits >= max_digits10 && !(digits == max_digits10 && (*start < max_lead || (*start == max_lead && result >> high_bit)));
  3664. }
  3665. if (negative)
  3666. {
  3667. // Workaround for crayc++ CC-3059: Expected no overflow in routine.
  3668. #ifdef _CRAYC
  3669. return (overflow || result > ~minv + 1) ? minv : ~result + 1;
  3670. #else
  3671. return (overflow || result > 0 - minv) ? minv : 0 - result;
  3672. #endif
  3673. }
  3674. else
  3675. return (overflow || result > maxv) ? maxv : result;
  3676. }
  3677. PUGI__FN int get_value_int(const char_t* value)
  3678. {
  3679. return string_to_integer<unsigned int>(value, static_cast<unsigned int>(INT_MIN), INT_MAX);
  3680. }
  3681. PUGI__FN unsigned int get_value_uint(const char_t* value)
  3682. {
  3683. return string_to_integer<unsigned int>(value, 0, UINT_MAX);
  3684. }
  3685. PUGI__FN double get_value_double(const char_t* value)
  3686. {
  3687. #ifdef PUGIXML_WCHAR_MODE
  3688. return wcstod(value, 0);
  3689. #else
  3690. return strtod(value, 0);
  3691. #endif
  3692. }
  3693. PUGI__FN float get_value_float(const char_t* value)
  3694. {
  3695. #ifdef PUGIXML_WCHAR_MODE
  3696. return static_cast<float>(wcstod(value, 0));
  3697. #else
  3698. return static_cast<float>(strtod(value, 0));
  3699. #endif
  3700. }
  3701. PUGI__FN bool get_value_bool(const char_t* value)
  3702. {
  3703. // only look at first char
  3704. char_t first = *value;
  3705. // 1*, t* (true), T* (True), y* (yes), Y* (YES)
  3706. return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');
  3707. }
  3708. #ifdef PUGIXML_HAS_LONG_LONG
  3709. PUGI__FN long long get_value_llong(const char_t* value)
  3710. {
  3711. return string_to_integer<unsigned long long>(value, static_cast<unsigned long long>(LLONG_MIN), LLONG_MAX);
  3712. }
  3713. PUGI__FN unsigned long long get_value_ullong(const char_t* value)
  3714. {
  3715. return string_to_integer<unsigned long long>(value, 0, ULLONG_MAX);
  3716. }
  3717. #endif
  3718. template <typename U> PUGI__FN PUGI__UNSIGNED_OVERFLOW char_t* integer_to_string(char_t* begin, char_t* end, U value, bool negative)
  3719. {
  3720. char_t* result = end - 1;
  3721. U rest = negative ? 0 - value : value;
  3722. do
  3723. {
  3724. *result-- = static_cast<char_t>('0' + (rest % 10));
  3725. rest /= 10;
  3726. }
  3727. while (rest);
  3728. assert(result >= begin);
  3729. (void)begin;
  3730. *result = '-';
  3731. return result + !negative;
  3732. }
  3733. // set value with conversion functions
  3734. template <typename String, typename Header>
  3735. PUGI__FN bool set_value_ascii(String& dest, Header& header, uintptr_t header_mask, char* buf)
  3736. {
  3737. #ifdef PUGIXML_WCHAR_MODE
  3738. char_t wbuf[128];
  3739. assert(strlen(buf) < sizeof(wbuf) / sizeof(wbuf[0]));
  3740. size_t offset = 0;
  3741. for (; buf[offset]; ++offset) wbuf[offset] = buf[offset];
  3742. return strcpy_insitu(dest, header, header_mask, wbuf, offset);
  3743. #else
  3744. return strcpy_insitu(dest, header, header_mask, buf, strlen(buf));
  3745. #endif
  3746. }
  3747. template <typename U, typename String, typename Header>
  3748. PUGI__FN bool set_value_integer(String& dest, Header& header, uintptr_t header_mask, U value, bool negative)
  3749. {
  3750. char_t buf[64];
  3751. char_t* end = buf + sizeof(buf) / sizeof(buf[0]);
  3752. char_t* begin = integer_to_string(buf, end, value, negative);
  3753. return strcpy_insitu(dest, header, header_mask, begin, end - begin);
  3754. }
  3755. template <typename String, typename Header>
  3756. PUGI__FN bool set_value_convert(String& dest, Header& header, uintptr_t header_mask, float value)
  3757. {
  3758. char buf[128];
  3759. PUGI__SNPRINTF(buf, "%.9g", double(value));
  3760. return set_value_ascii(dest, header, header_mask, buf);
  3761. }
  3762. template <typename String, typename Header>
  3763. PUGI__FN bool set_value_convert(String& dest, Header& header, uintptr_t header_mask, double value)
  3764. {
  3765. char buf[128];
  3766. PUGI__SNPRINTF(buf, "%.17g", value);
  3767. return set_value_ascii(dest, header, header_mask, buf);
  3768. }
  3769. template <typename String, typename Header>
  3770. PUGI__FN bool set_value_bool(String& dest, Header& header, uintptr_t header_mask, bool value)
  3771. {
  3772. return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"), value ? 4 : 5);
  3773. }
  3774. PUGI__FN xml_parse_result load_buffer_impl(xml_document_struct* doc, xml_node_struct* root, void* contents, size_t size, unsigned int options, xml_encoding encoding, bool is_mutable, bool own, char_t** out_buffer)
  3775. {
  3776. // check input buffer
  3777. if (!contents && size) return make_parse_result(status_io_error);
  3778. // get actual encoding
  3779. xml_encoding buffer_encoding = impl::get_buffer_encoding(encoding, contents, size);
  3780. // get private buffer
  3781. char_t* buffer = 0;
  3782. size_t length = 0;
  3783. // coverity[var_deref_model]
  3784. if (!impl::convert_buffer(buffer, length, buffer_encoding, contents, size, is_mutable)) return impl::make_parse_result(status_out_of_memory);
  3785. // delete original buffer if we performed a conversion
  3786. if (own && buffer != contents && contents) impl::xml_memory::deallocate(contents);
  3787. // grab onto buffer if it's our buffer, user is responsible for deallocating contents himself
  3788. if (own || buffer != contents) *out_buffer = buffer;
  3789. // store buffer for offset_debug
  3790. doc->buffer = buffer;
  3791. // parse
  3792. xml_parse_result res = impl::xml_parser::parse(buffer, length, doc, root, options);
  3793. // remember encoding
  3794. res.encoding = buffer_encoding;
  3795. return res;
  3796. }
  3797. // 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
  3798. PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result)
  3799. {
  3800. #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
  3801. // there are 64-bit versions of fseek/ftell, let's use them
  3802. typedef __int64 length_type;
  3803. _fseeki64(file, 0, SEEK_END);
  3804. length_type length = _ftelli64(file);
  3805. _fseeki64(file, 0, SEEK_SET);
  3806. #elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR))
  3807. // there are 64-bit versions of fseek/ftell, let's use them
  3808. typedef off64_t length_type;
  3809. fseeko64(file, 0, SEEK_END);
  3810. length_type length = ftello64(file);
  3811. fseeko64(file, 0, SEEK_SET);
  3812. #else
  3813. // 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.
  3814. typedef long length_type;
  3815. fseek(file, 0, SEEK_END);
  3816. length_type length = ftell(file);
  3817. fseek(file, 0, SEEK_SET);
  3818. #endif
  3819. // check for I/O errors
  3820. if (length < 0) return status_io_error;
  3821. // check for overflow
  3822. size_t result = static_cast<size_t>(length);
  3823. if (static_cast<length_type>(result) != length) return status_out_of_memory;
  3824. // finalize
  3825. out_result = result;
  3826. return status_ok;
  3827. }
  3828. // This function assumes that buffer has extra sizeof(char_t) writable bytes after size
  3829. PUGI__FN size_t zero_terminate_buffer(void* buffer, size_t size, xml_encoding encoding)
  3830. {
  3831. // We only need to zero-terminate if encoding conversion does not do it for us
  3832. #ifdef PUGIXML_WCHAR_MODE
  3833. xml_encoding wchar_encoding = get_wchar_encoding();
  3834. if (encoding == wchar_encoding || need_endian_swap_utf(encoding, wchar_encoding))
  3835. {
  3836. size_t length = size / sizeof(char_t);
  3837. static_cast<char_t*>(buffer)[length] = 0;
  3838. return (length + 1) * sizeof(char_t);
  3839. }
  3840. #else
  3841. if (encoding == encoding_utf8)
  3842. {
  3843. static_cast<char*>(buffer)[size] = 0;
  3844. return size + 1;
  3845. }
  3846. #endif
  3847. return size;
  3848. }
  3849. PUGI__FN xml_parse_result load_file_impl(xml_document_struct* doc, FILE* file, unsigned int options, xml_encoding encoding, char_t** out_buffer)
  3850. {
  3851. if (!file) return make_parse_result(status_file_not_found);
  3852. // get file size (can result in I/O errors)
  3853. size_t size = 0;
  3854. xml_parse_status size_status = get_file_size(file, size);
  3855. if (size_status != status_ok) return make_parse_result(size_status);
  3856. size_t max_suffix_size = sizeof(char_t);
  3857. // allocate buffer for the whole file
  3858. char* contents = static_cast<char*>(xml_memory::allocate(size + max_suffix_size));
  3859. if (!contents) return make_parse_result(status_out_of_memory);
  3860. // read file in memory
  3861. size_t read_size = fread(contents, 1, size, file);
  3862. if (read_size != size)
  3863. {
  3864. xml_memory::deallocate(contents);
  3865. return make_parse_result(status_io_error);
  3866. }
  3867. xml_encoding real_encoding = get_buffer_encoding(encoding, contents, size);
  3868. return load_buffer_impl(doc, doc, contents, zero_terminate_buffer(contents, size, real_encoding), options, real_encoding, true, true, out_buffer);
  3869. }
  3870. PUGI__FN void close_file(FILE* file)
  3871. {
  3872. fclose(file);
  3873. }
  3874. #ifndef PUGIXML_NO_STL
  3875. template <typename T> struct xml_stream_chunk
  3876. {
  3877. static xml_stream_chunk* create()
  3878. {
  3879. void* memory = xml_memory::allocate(sizeof(xml_stream_chunk));
  3880. if (!memory) return 0;
  3881. return new (memory) xml_stream_chunk();
  3882. }
  3883. static void destroy(xml_stream_chunk* chunk)
  3884. {
  3885. // free chunk chain
  3886. while (chunk)
  3887. {
  3888. xml_stream_chunk* next_ = chunk->next;
  3889. xml_memory::deallocate(chunk);
  3890. chunk = next_;
  3891. }
  3892. }
  3893. xml_stream_chunk(): next(0), size(0)
  3894. {
  3895. }
  3896. xml_stream_chunk* next;
  3897. size_t size;
  3898. T data[xml_memory_page_size / sizeof(T)];
  3899. };
  3900. template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
  3901. {
  3902. auto_deleter<xml_stream_chunk<T> > chunks(0, xml_stream_chunk<T>::destroy);
  3903. // read file to a chunk list
  3904. size_t total = 0;
  3905. xml_stream_chunk<T>* last = 0;
  3906. while (!stream.eof())
  3907. {
  3908. // allocate new chunk
  3909. xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create();
  3910. if (!chunk) return status_out_of_memory;
  3911. // append chunk to list
  3912. if (last) last = last->next = chunk;
  3913. else chunks.data = last = chunk;
  3914. // read data to chunk
  3915. stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T)));
  3916. chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T);
  3917. // read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors
  3918. if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
  3919. // guard against huge files (chunk size is small enough to make this overflow check work)
  3920. if (total + chunk->size < total) return status_out_of_memory;
  3921. total += chunk->size;
  3922. }
  3923. size_t max_suffix_size = sizeof(char_t);
  3924. // copy chunk list to a contiguous buffer
  3925. char* buffer = static_cast<char*>(xml_memory::allocate(total + max_suffix_size));
  3926. if (!buffer) return status_out_of_memory;
  3927. char* write = buffer;
  3928. for (xml_stream_chunk<T>* chunk = chunks.data; chunk; chunk = chunk->next)
  3929. {
  3930. assert(write + chunk->size <= buffer + total);
  3931. memcpy(write, chunk->data, chunk->size);
  3932. write += chunk->size;
  3933. }
  3934. assert(write == buffer + total);
  3935. // return buffer
  3936. *out_buffer = buffer;
  3937. *out_size = total;
  3938. return status_ok;
  3939. }
  3940. template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
  3941. {
  3942. // get length of remaining data in stream
  3943. typename std::basic_istream<T>::pos_type pos = stream.tellg();
  3944. stream.seekg(0, std::ios::end);
  3945. std::streamoff length = stream.tellg() - pos;
  3946. stream.seekg(pos);
  3947. if (stream.fail() || pos < 0) return status_io_error;
  3948. // guard against huge files
  3949. size_t read_length = static_cast<size_t>(length);
  3950. if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory;
  3951. size_t max_suffix_size = sizeof(char_t);
  3952. // read stream data into memory (guard against stream exceptions with buffer holder)
  3953. auto_deleter<void> buffer(xml_memory::allocate(read_length * sizeof(T) + max_suffix_size), xml_memory::deallocate);
  3954. if (!buffer.data) return status_out_of_memory;
  3955. stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length));
  3956. // 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
  3957. if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
  3958. // return buffer
  3959. size_t actual_length = static_cast<size_t>(stream.gcount());
  3960. assert(actual_length <= read_length);
  3961. *out_buffer = buffer.release();
  3962. *out_size = actual_length * sizeof(T);
  3963. return status_ok;
  3964. }
  3965. template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document_struct* doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding, char_t** out_buffer)
  3966. {
  3967. void* buffer = 0;
  3968. size_t size = 0;
  3969. xml_parse_status status = status_ok;
  3970. // if stream has an error bit set, bail out (otherwise tellg() can fail and we'll clear error bits)
  3971. if (stream.fail()) return make_parse_result(status_io_error);
  3972. // load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory)
  3973. if (stream.tellg() < 0)
  3974. {
  3975. stream.clear(); // clear error flags that could be set by a failing tellg
  3976. status = load_stream_data_noseek(stream, &buffer, &size);
  3977. }
  3978. else
  3979. status = load_stream_data_seek(stream, &buffer, &size);
  3980. if (status != status_ok) return make_parse_result(status);
  3981. xml_encoding real_encoding = get_buffer_encoding(encoding, buffer, size);
  3982. return load_buffer_impl(doc, doc, buffer, zero_terminate_buffer(buffer, size, real_encoding), options, real_encoding, true, true, out_buffer);
  3983. }
  3984. #endif
  3985. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && (!defined(__STRICT_ANSI__) || defined(__MINGW64_VERSION_MAJOR)))
  3986. PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
  3987. {
  3988. return _wfopen(path, mode);
  3989. }
  3990. #else
  3991. PUGI__FN char* convert_path_heap(const wchar_t* str)
  3992. {
  3993. assert(str);
  3994. // first pass: get length in utf8 characters
  3995. size_t length = strlength_wide(str);
  3996. size_t size = as_utf8_begin(str, length);
  3997. // allocate resulting string
  3998. char* result = static_cast<char*>(xml_memory::allocate(size + 1));
  3999. if (!result) return 0;
  4000. // second pass: convert to utf8
  4001. as_utf8_end(result, size, str, length);
  4002. // zero-terminate
  4003. result[size] = 0;
  4004. return result;
  4005. }
  4006. PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
  4007. {
  4008. // there is no standard function to open wide paths, so our best bet is to try utf8 path
  4009. char* path_utf8 = convert_path_heap(path);
  4010. if (!path_utf8) return 0;
  4011. // convert mode to ASCII (we mirror _wfopen interface)
  4012. char mode_ascii[4] = {0};
  4013. for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]);
  4014. // try to open the utf8 path
  4015. FILE* result = fopen(path_utf8, mode_ascii);
  4016. // free dummy buffer
  4017. xml_memory::deallocate(path_utf8);
  4018. return result;
  4019. }
  4020. #endif
  4021. PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding)
  4022. {
  4023. if (!file) return false;
  4024. xml_writer_file writer(file);
  4025. doc.save(writer, indent, flags, encoding);
  4026. return ferror(file) == 0;
  4027. }
  4028. struct name_null_sentry
  4029. {
  4030. xml_node_struct* node;
  4031. char_t* name;
  4032. name_null_sentry(xml_node_struct* node_): node(node_), name(node_->name)
  4033. {
  4034. node->name = 0;
  4035. }
  4036. ~name_null_sentry()
  4037. {
  4038. node->name = name;
  4039. }
  4040. };
  4041. PUGI__NS_END
  4042. namespace pugi
  4043. {
  4044. PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_)
  4045. {
  4046. }
  4047. PUGI__FN void xml_writer_file::write(const void* data, size_t size)
  4048. {
  4049. size_t result = fwrite(data, 1, size, static_cast<FILE*>(file));
  4050. (void)!result; // unfortunately we can't do proper error handling here
  4051. }
  4052. #ifndef PUGIXML_NO_STL
  4053. PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0)
  4054. {
  4055. }
  4056. 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)
  4057. {
  4058. }
  4059. PUGI__FN void xml_writer_stream::write(const void* data, size_t size)
  4060. {
  4061. if (narrow_stream)
  4062. {
  4063. assert(!wide_stream);
  4064. narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
  4065. }
  4066. else
  4067. {
  4068. assert(wide_stream);
  4069. assert(size % sizeof(wchar_t) == 0);
  4070. wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t)));
  4071. }
  4072. }
  4073. #endif
  4074. PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0)
  4075. {
  4076. }
  4077. PUGI__FN xml_tree_walker::~xml_tree_walker()
  4078. {
  4079. }
  4080. PUGI__FN int xml_tree_walker::depth() const
  4081. {
  4082. return _depth;
  4083. }
  4084. PUGI__FN bool xml_tree_walker::begin(xml_node&)
  4085. {
  4086. return true;
  4087. }
  4088. PUGI__FN bool xml_tree_walker::end(xml_node&)
  4089. {
  4090. return true;
  4091. }
  4092. PUGI__FN xml_attribute::xml_attribute(): _attr(0)
  4093. {
  4094. }
  4095. PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr)
  4096. {
  4097. }
  4098. PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***)
  4099. {
  4100. }
  4101. PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const
  4102. {
  4103. return _attr ? unspecified_bool_xml_attribute : 0;
  4104. }
  4105. PUGI__FN bool xml_attribute::operator!() const
  4106. {
  4107. return !_attr;
  4108. }
  4109. PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const
  4110. {
  4111. return (_attr == r._attr);
  4112. }
  4113. PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const
  4114. {
  4115. return (_attr != r._attr);
  4116. }
  4117. PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const
  4118. {
  4119. return (_attr < r._attr);
  4120. }
  4121. PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const
  4122. {
  4123. return (_attr > r._attr);
  4124. }
  4125. PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const
  4126. {
  4127. return (_attr <= r._attr);
  4128. }
  4129. PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const
  4130. {
  4131. return (_attr >= r._attr);
  4132. }
  4133. PUGI__FN xml_attribute xml_attribute::next_attribute() const
  4134. {
  4135. return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute();
  4136. }
  4137. PUGI__FN xml_attribute xml_attribute::previous_attribute() const
  4138. {
  4139. return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute();
  4140. }
  4141. PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const
  4142. {
  4143. return (_attr && _attr->value) ? _attr->value + 0 : def;
  4144. }
  4145. PUGI__FN int xml_attribute::as_int(int def) const
  4146. {
  4147. return (_attr && _attr->value) ? impl::get_value_int(_attr->value) : def;
  4148. }
  4149. PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const
  4150. {
  4151. return (_attr && _attr->value) ? impl::get_value_uint(_attr->value) : def;
  4152. }
  4153. PUGI__FN double xml_attribute::as_double(double def) const
  4154. {
  4155. return (_attr && _attr->value) ? impl::get_value_double(_attr->value) : def;
  4156. }
  4157. PUGI__FN float xml_attribute::as_float(float def) const
  4158. {
  4159. return (_attr && _attr->value) ? impl::get_value_float(_attr->value) : def;
  4160. }
  4161. PUGI__FN bool xml_attribute::as_bool(bool def) const
  4162. {
  4163. return (_attr && _attr->value) ? impl::get_value_bool(_attr->value) : def;
  4164. }
  4165. #ifdef PUGIXML_HAS_LONG_LONG
  4166. PUGI__FN long long xml_attribute::as_llong(long long def) const
  4167. {
  4168. return (_attr && _attr->value) ? impl::get_value_llong(_attr->value) : def;
  4169. }
  4170. PUGI__FN unsigned long long xml_attribute::as_ullong(unsigned long long def) const
  4171. {
  4172. return (_attr && _attr->value) ? impl::get_value_ullong(_attr->value) : def;
  4173. }
  4174. #endif
  4175. PUGI__FN bool xml_attribute::empty() const
  4176. {
  4177. return !_attr;
  4178. }
  4179. PUGI__FN const char_t* xml_attribute::name() const
  4180. {
  4181. return (_attr && _attr->name) ? _attr->name + 0 : PUGIXML_TEXT("");
  4182. }
  4183. PUGI__FN const char_t* xml_attribute::value() const
  4184. {
  4185. return (_attr && _attr->value) ? _attr->value + 0 : PUGIXML_TEXT("");
  4186. }
  4187. PUGI__FN size_t xml_attribute::hash_value() const
  4188. {
  4189. return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct));
  4190. }
  4191. PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const
  4192. {
  4193. return _attr;
  4194. }
  4195. PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs)
  4196. {
  4197. set_value(rhs);
  4198. return *this;
  4199. }
  4200. PUGI__FN xml_attribute& xml_attribute::operator=(int rhs)
  4201. {
  4202. set_value(rhs);
  4203. return *this;
  4204. }
  4205. PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs)
  4206. {
  4207. set_value(rhs);
  4208. return *this;
  4209. }
  4210. PUGI__FN xml_attribute& xml_attribute::operator=(long rhs)
  4211. {
  4212. set_value(rhs);
  4213. return *this;
  4214. }
  4215. PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long rhs)
  4216. {
  4217. set_value(rhs);
  4218. return *this;
  4219. }
  4220. PUGI__FN xml_attribute& xml_attribute::operator=(double rhs)
  4221. {
  4222. set_value(rhs);
  4223. return *this;
  4224. }
  4225. PUGI__FN xml_attribute& xml_attribute::operator=(float rhs)
  4226. {
  4227. set_value(rhs);
  4228. return *this;
  4229. }
  4230. PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs)
  4231. {
  4232. set_value(rhs);
  4233. return *this;
  4234. }
  4235. #ifdef PUGIXML_HAS_LONG_LONG
  4236. PUGI__FN xml_attribute& xml_attribute::operator=(long long rhs)
  4237. {
  4238. set_value(rhs);
  4239. return *this;
  4240. }
  4241. PUGI__FN xml_attribute& xml_attribute::operator=(unsigned long long rhs)
  4242. {
  4243. set_value(rhs);
  4244. return *this;
  4245. }
  4246. #endif
  4247. PUGI__FN bool xml_attribute::set_name(const char_t* rhs)
  4248. {
  4249. if (!_attr) return false;
  4250. return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs, impl::strlength(rhs));
  4251. }
  4252. PUGI__FN bool xml_attribute::set_value(const char_t* rhs)
  4253. {
  4254. if (!_attr) return false;
  4255. return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs));
  4256. }
  4257. PUGI__FN bool xml_attribute::set_value(int rhs)
  4258. {
  4259. if (!_attr) return false;
  4260. return impl::set_value_integer<unsigned int>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0);
  4261. }
  4262. PUGI__FN bool xml_attribute::set_value(unsigned int rhs)
  4263. {
  4264. if (!_attr) return false;
  4265. return impl::set_value_integer<unsigned int>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false);
  4266. }
  4267. PUGI__FN bool xml_attribute::set_value(long rhs)
  4268. {
  4269. if (!_attr) return false;
  4270. return impl::set_value_integer<unsigned long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0);
  4271. }
  4272. PUGI__FN bool xml_attribute::set_value(unsigned long rhs)
  4273. {
  4274. if (!_attr) return false;
  4275. return impl::set_value_integer<unsigned long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false);
  4276. }
  4277. PUGI__FN bool xml_attribute::set_value(double rhs)
  4278. {
  4279. if (!_attr) return false;
  4280. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  4281. }
  4282. PUGI__FN bool xml_attribute::set_value(float rhs)
  4283. {
  4284. if (!_attr) return false;
  4285. return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  4286. }
  4287. PUGI__FN bool xml_attribute::set_value(bool rhs)
  4288. {
  4289. if (!_attr) return false;
  4290. return impl::set_value_bool(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
  4291. }
  4292. #ifdef PUGIXML_HAS_LONG_LONG
  4293. PUGI__FN bool xml_attribute::set_value(long long rhs)
  4294. {
  4295. if (!_attr) return false;
  4296. return impl::set_value_integer<unsigned long long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0);
  4297. }
  4298. PUGI__FN bool xml_attribute::set_value(unsigned long long rhs)
  4299. {
  4300. if (!_attr) return false;
  4301. return impl::set_value_integer<unsigned long long>(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs, false);
  4302. }
  4303. #endif
  4304. #ifdef __BORLANDC__
  4305. PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs)
  4306. {
  4307. return (bool)lhs && rhs;
  4308. }
  4309. PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs)
  4310. {
  4311. return (bool)lhs || rhs;
  4312. }
  4313. #endif
  4314. PUGI__FN xml_node::xml_node(): _root(0)
  4315. {
  4316. }
  4317. PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p)
  4318. {
  4319. }
  4320. PUGI__FN static void unspecified_bool_xml_node(xml_node***)
  4321. {
  4322. }
  4323. PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const
  4324. {
  4325. return _root ? unspecified_bool_xml_node : 0;
  4326. }
  4327. PUGI__FN bool xml_node::operator!() const
  4328. {
  4329. return !_root;
  4330. }
  4331. PUGI__FN xml_node::iterator xml_node::begin() const
  4332. {
  4333. return iterator(_root ? _root->first_child + 0 : 0, _root);
  4334. }
  4335. PUGI__FN xml_node::iterator xml_node::end() const
  4336. {
  4337. return iterator(0, _root);
  4338. }
  4339. PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const
  4340. {
  4341. return attribute_iterator(_root ? _root->first_attribute + 0 : 0, _root);
  4342. }
  4343. PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const
  4344. {
  4345. return attribute_iterator(0, _root);
  4346. }
  4347. PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const
  4348. {
  4349. return xml_object_range<xml_node_iterator>(begin(), end());
  4350. }
  4351. PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const
  4352. {
  4353. return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_)._root, _root, name_), xml_named_node_iterator(0, _root, name_));
  4354. }
  4355. PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const
  4356. {
  4357. return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end());
  4358. }
  4359. PUGI__FN bool xml_node::operator==(const xml_node& r) const
  4360. {
  4361. return (_root == r._root);
  4362. }
  4363. PUGI__FN bool xml_node::operator!=(const xml_node& r) const
  4364. {
  4365. return (_root != r._root);
  4366. }
  4367. PUGI__FN bool xml_node::operator<(const xml_node& r) const
  4368. {
  4369. return (_root < r._root);
  4370. }
  4371. PUGI__FN bool xml_node::operator>(const xml_node& r) const
  4372. {
  4373. return (_root > r._root);
  4374. }
  4375. PUGI__FN bool xml_node::operator<=(const xml_node& r) const
  4376. {
  4377. return (_root <= r._root);
  4378. }
  4379. PUGI__FN bool xml_node::operator>=(const xml_node& r) const
  4380. {
  4381. return (_root >= r._root);
  4382. }
  4383. PUGI__FN bool xml_node::empty() const
  4384. {
  4385. return !_root;
  4386. }
  4387. PUGI__FN const char_t* xml_node::name() const
  4388. {
  4389. return (_root && _root->name) ? _root->name + 0 : PUGIXML_TEXT("");
  4390. }
  4391. PUGI__FN xml_node_type xml_node::type() const
  4392. {
  4393. return _root ? PUGI__NODETYPE(_root) : node_null;
  4394. }
  4395. PUGI__FN const char_t* xml_node::value() const
  4396. {
  4397. return (_root && _root->value) ? _root->value + 0 : PUGIXML_TEXT("");
  4398. }
  4399. PUGI__FN xml_node xml_node::child(const char_t* name_) const
  4400. {
  4401. if (!_root) return xml_node();
  4402. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4403. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  4404. return xml_node();
  4405. }
  4406. PUGI__FN xml_attribute xml_node::attribute(const char_t* name_) const
  4407. {
  4408. if (!_root) return xml_attribute();
  4409. for (xml_attribute_struct* i = _root->first_attribute; i; i = i->next_attribute)
  4410. if (i->name && impl::strequal(name_, i->name))
  4411. return xml_attribute(i);
  4412. return xml_attribute();
  4413. }
  4414. PUGI__FN xml_node xml_node::next_sibling(const char_t* name_) const
  4415. {
  4416. if (!_root) return xml_node();
  4417. for (xml_node_struct* i = _root->next_sibling; i; i = i->next_sibling)
  4418. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  4419. return xml_node();
  4420. }
  4421. PUGI__FN xml_node xml_node::next_sibling() const
  4422. {
  4423. return _root ? xml_node(_root->next_sibling) : xml_node();
  4424. }
  4425. PUGI__FN xml_node xml_node::previous_sibling(const char_t* name_) const
  4426. {
  4427. if (!_root) return xml_node();
  4428. for (xml_node_struct* i = _root->prev_sibling_c; i->next_sibling; i = i->prev_sibling_c)
  4429. if (i->name && impl::strequal(name_, i->name)) return xml_node(i);
  4430. return xml_node();
  4431. }
  4432. PUGI__FN xml_attribute xml_node::attribute(const char_t* name_, xml_attribute& hint_) const
  4433. {
  4434. xml_attribute_struct* hint = hint_._attr;
  4435. // if hint is not an attribute of node, behavior is not defined
  4436. assert(!hint || (_root && impl::is_attribute_of(hint, _root)));
  4437. if (!_root) return xml_attribute();
  4438. // optimistically search from hint up until the end
  4439. for (xml_attribute_struct* i = hint; i; i = i->next_attribute)
  4440. if (i->name && impl::strequal(name_, i->name))
  4441. {
  4442. // update hint to maximize efficiency of searching for consecutive attributes
  4443. hint_._attr = i->next_attribute;
  4444. return xml_attribute(i);
  4445. }
  4446. // wrap around and search from the first attribute until the hint
  4447. // 'j' null pointer check is technically redundant, but it prevents a crash in case the assertion above fails
  4448. for (xml_attribute_struct* j = _root->first_attribute; j && j != hint; j = j->next_attribute)
  4449. if (j->name && impl::strequal(name_, j->name))
  4450. {
  4451. // update hint to maximize efficiency of searching for consecutive attributes
  4452. hint_._attr = j->next_attribute;
  4453. return xml_attribute(j);
  4454. }
  4455. return xml_attribute();
  4456. }
  4457. PUGI__FN xml_node xml_node::previous_sibling() const
  4458. {
  4459. if (!_root) return xml_node();
  4460. if (_root->prev_sibling_c->next_sibling) return xml_node(_root->prev_sibling_c);
  4461. else return xml_node();
  4462. }
  4463. PUGI__FN xml_node xml_node::parent() const
  4464. {
  4465. return _root ? xml_node(_root->parent) : xml_node();
  4466. }
  4467. PUGI__FN xml_node xml_node::root() const
  4468. {
  4469. return _root ? xml_node(&impl::get_document(_root)) : xml_node();
  4470. }
  4471. PUGI__FN xml_text xml_node::text() const
  4472. {
  4473. return xml_text(_root);
  4474. }
  4475. PUGI__FN const char_t* xml_node::child_value() const
  4476. {
  4477. if (!_root) return PUGIXML_TEXT("");
  4478. // element nodes can have value if parse_embed_pcdata was used
  4479. if (PUGI__NODETYPE(_root) == node_element && _root->value)
  4480. return _root->value;
  4481. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4482. if (impl::is_text_node(i) && i->value)
  4483. return i->value;
  4484. return PUGIXML_TEXT("");
  4485. }
  4486. PUGI__FN const char_t* xml_node::child_value(const char_t* name_) const
  4487. {
  4488. return child(name_).child_value();
  4489. }
  4490. PUGI__FN xml_attribute xml_node::first_attribute() const
  4491. {
  4492. return _root ? xml_attribute(_root->first_attribute) : xml_attribute();
  4493. }
  4494. PUGI__FN xml_attribute xml_node::last_attribute() const
  4495. {
  4496. return _root && _root->first_attribute ? xml_attribute(_root->first_attribute->prev_attribute_c) : xml_attribute();
  4497. }
  4498. PUGI__FN xml_node xml_node::first_child() const
  4499. {
  4500. return _root ? xml_node(_root->first_child) : xml_node();
  4501. }
  4502. PUGI__FN xml_node xml_node::last_child() const
  4503. {
  4504. return _root && _root->first_child ? xml_node(_root->first_child->prev_sibling_c) : xml_node();
  4505. }
  4506. PUGI__FN bool xml_node::set_name(const char_t* rhs)
  4507. {
  4508. xml_node_type type_ = _root ? PUGI__NODETYPE(_root) : node_null;
  4509. if (type_ != node_element && type_ != node_pi && type_ != node_declaration)
  4510. return false;
  4511. return impl::strcpy_insitu(_root->name, _root->header, impl::xml_memory_page_name_allocated_mask, rhs, impl::strlength(rhs));
  4512. }
  4513. PUGI__FN bool xml_node::set_value(const char_t* rhs)
  4514. {
  4515. xml_node_type type_ = _root ? PUGI__NODETYPE(_root) : node_null;
  4516. if (type_ != node_pcdata && type_ != node_cdata && type_ != node_comment && type_ != node_pi && type_ != node_doctype)
  4517. return false;
  4518. return impl::strcpy_insitu(_root->value, _root->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs));
  4519. }
  4520. PUGI__FN xml_attribute xml_node::append_attribute(const char_t* name_)
  4521. {
  4522. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4523. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4524. if (!alloc.reserve()) return xml_attribute();
  4525. xml_attribute a(impl::allocate_attribute(alloc));
  4526. if (!a) return xml_attribute();
  4527. impl::append_attribute(a._attr, _root);
  4528. a.set_name(name_);
  4529. return a;
  4530. }
  4531. PUGI__FN xml_attribute xml_node::prepend_attribute(const char_t* name_)
  4532. {
  4533. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4534. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4535. if (!alloc.reserve()) return xml_attribute();
  4536. xml_attribute a(impl::allocate_attribute(alloc));
  4537. if (!a) return xml_attribute();
  4538. impl::prepend_attribute(a._attr, _root);
  4539. a.set_name(name_);
  4540. return a;
  4541. }
  4542. PUGI__FN xml_attribute xml_node::insert_attribute_after(const char_t* name_, const xml_attribute& attr)
  4543. {
  4544. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4545. if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
  4546. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4547. if (!alloc.reserve()) return xml_attribute();
  4548. xml_attribute a(impl::allocate_attribute(alloc));
  4549. if (!a) return xml_attribute();
  4550. impl::insert_attribute_after(a._attr, attr._attr, _root);
  4551. a.set_name(name_);
  4552. return a;
  4553. }
  4554. PUGI__FN xml_attribute xml_node::insert_attribute_before(const char_t* name_, const xml_attribute& attr)
  4555. {
  4556. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4557. if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
  4558. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4559. if (!alloc.reserve()) return xml_attribute();
  4560. xml_attribute a(impl::allocate_attribute(alloc));
  4561. if (!a) return xml_attribute();
  4562. impl::insert_attribute_before(a._attr, attr._attr, _root);
  4563. a.set_name(name_);
  4564. return a;
  4565. }
  4566. PUGI__FN xml_attribute xml_node::append_copy(const xml_attribute& proto)
  4567. {
  4568. if (!proto) return xml_attribute();
  4569. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4570. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4571. if (!alloc.reserve()) return xml_attribute();
  4572. xml_attribute a(impl::allocate_attribute(alloc));
  4573. if (!a) return xml_attribute();
  4574. impl::append_attribute(a._attr, _root);
  4575. impl::node_copy_attribute(a._attr, proto._attr);
  4576. return a;
  4577. }
  4578. PUGI__FN xml_attribute xml_node::prepend_copy(const xml_attribute& proto)
  4579. {
  4580. if (!proto) return xml_attribute();
  4581. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4582. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4583. if (!alloc.reserve()) return xml_attribute();
  4584. xml_attribute a(impl::allocate_attribute(alloc));
  4585. if (!a) return xml_attribute();
  4586. impl::prepend_attribute(a._attr, _root);
  4587. impl::node_copy_attribute(a._attr, proto._attr);
  4588. return a;
  4589. }
  4590. PUGI__FN xml_attribute xml_node::insert_copy_after(const xml_attribute& proto, const xml_attribute& attr)
  4591. {
  4592. if (!proto) return xml_attribute();
  4593. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4594. if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
  4595. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4596. if (!alloc.reserve()) return xml_attribute();
  4597. xml_attribute a(impl::allocate_attribute(alloc));
  4598. if (!a) return xml_attribute();
  4599. impl::insert_attribute_after(a._attr, attr._attr, _root);
  4600. impl::node_copy_attribute(a._attr, proto._attr);
  4601. return a;
  4602. }
  4603. PUGI__FN xml_attribute xml_node::insert_copy_before(const xml_attribute& proto, const xml_attribute& attr)
  4604. {
  4605. if (!proto) return xml_attribute();
  4606. if (!impl::allow_insert_attribute(type())) return xml_attribute();
  4607. if (!attr || !impl::is_attribute_of(attr._attr, _root)) return xml_attribute();
  4608. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4609. if (!alloc.reserve()) return xml_attribute();
  4610. xml_attribute a(impl::allocate_attribute(alloc));
  4611. if (!a) return xml_attribute();
  4612. impl::insert_attribute_before(a._attr, attr._attr, _root);
  4613. impl::node_copy_attribute(a._attr, proto._attr);
  4614. return a;
  4615. }
  4616. PUGI__FN xml_node xml_node::append_child(xml_node_type type_)
  4617. {
  4618. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4619. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4620. if (!alloc.reserve()) return xml_node();
  4621. xml_node n(impl::allocate_node(alloc, type_));
  4622. if (!n) return xml_node();
  4623. impl::append_node(n._root, _root);
  4624. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  4625. return n;
  4626. }
  4627. PUGI__FN xml_node xml_node::prepend_child(xml_node_type type_)
  4628. {
  4629. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4630. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4631. if (!alloc.reserve()) return xml_node();
  4632. xml_node n(impl::allocate_node(alloc, type_));
  4633. if (!n) return xml_node();
  4634. impl::prepend_node(n._root, _root);
  4635. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  4636. return n;
  4637. }
  4638. PUGI__FN xml_node xml_node::insert_child_before(xml_node_type type_, const xml_node& node)
  4639. {
  4640. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4641. if (!node._root || node._root->parent != _root) return xml_node();
  4642. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4643. if (!alloc.reserve()) return xml_node();
  4644. xml_node n(impl::allocate_node(alloc, type_));
  4645. if (!n) return xml_node();
  4646. impl::insert_node_before(n._root, node._root);
  4647. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  4648. return n;
  4649. }
  4650. PUGI__FN xml_node xml_node::insert_child_after(xml_node_type type_, const xml_node& node)
  4651. {
  4652. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4653. if (!node._root || node._root->parent != _root) return xml_node();
  4654. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4655. if (!alloc.reserve()) return xml_node();
  4656. xml_node n(impl::allocate_node(alloc, type_));
  4657. if (!n) return xml_node();
  4658. impl::insert_node_after(n._root, node._root);
  4659. if (type_ == node_declaration) n.set_name(PUGIXML_TEXT("xml"));
  4660. return n;
  4661. }
  4662. PUGI__FN xml_node xml_node::append_child(const char_t* name_)
  4663. {
  4664. xml_node result = append_child(node_element);
  4665. result.set_name(name_);
  4666. return result;
  4667. }
  4668. PUGI__FN xml_node xml_node::prepend_child(const char_t* name_)
  4669. {
  4670. xml_node result = prepend_child(node_element);
  4671. result.set_name(name_);
  4672. return result;
  4673. }
  4674. PUGI__FN xml_node xml_node::insert_child_after(const char_t* name_, const xml_node& node)
  4675. {
  4676. xml_node result = insert_child_after(node_element, node);
  4677. result.set_name(name_);
  4678. return result;
  4679. }
  4680. PUGI__FN xml_node xml_node::insert_child_before(const char_t* name_, const xml_node& node)
  4681. {
  4682. xml_node result = insert_child_before(node_element, node);
  4683. result.set_name(name_);
  4684. return result;
  4685. }
  4686. PUGI__FN xml_node xml_node::append_copy(const xml_node& proto)
  4687. {
  4688. xml_node_type type_ = proto.type();
  4689. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4690. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4691. if (!alloc.reserve()) return xml_node();
  4692. xml_node n(impl::allocate_node(alloc, type_));
  4693. if (!n) return xml_node();
  4694. impl::append_node(n._root, _root);
  4695. impl::node_copy_tree(n._root, proto._root);
  4696. return n;
  4697. }
  4698. PUGI__FN xml_node xml_node::prepend_copy(const xml_node& proto)
  4699. {
  4700. xml_node_type type_ = proto.type();
  4701. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4702. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4703. if (!alloc.reserve()) return xml_node();
  4704. xml_node n(impl::allocate_node(alloc, type_));
  4705. if (!n) return xml_node();
  4706. impl::prepend_node(n._root, _root);
  4707. impl::node_copy_tree(n._root, proto._root);
  4708. return n;
  4709. }
  4710. PUGI__FN xml_node xml_node::insert_copy_after(const xml_node& proto, const xml_node& node)
  4711. {
  4712. xml_node_type type_ = proto.type();
  4713. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4714. if (!node._root || node._root->parent != _root) return xml_node();
  4715. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4716. if (!alloc.reserve()) return xml_node();
  4717. xml_node n(impl::allocate_node(alloc, type_));
  4718. if (!n) return xml_node();
  4719. impl::insert_node_after(n._root, node._root);
  4720. impl::node_copy_tree(n._root, proto._root);
  4721. return n;
  4722. }
  4723. PUGI__FN xml_node xml_node::insert_copy_before(const xml_node& proto, const xml_node& node)
  4724. {
  4725. xml_node_type type_ = proto.type();
  4726. if (!impl::allow_insert_child(type(), type_)) return xml_node();
  4727. if (!node._root || node._root->parent != _root) return xml_node();
  4728. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4729. if (!alloc.reserve()) return xml_node();
  4730. xml_node n(impl::allocate_node(alloc, type_));
  4731. if (!n) return xml_node();
  4732. impl::insert_node_before(n._root, node._root);
  4733. impl::node_copy_tree(n._root, proto._root);
  4734. return n;
  4735. }
  4736. PUGI__FN xml_node xml_node::append_move(const xml_node& moved)
  4737. {
  4738. if (!impl::allow_move(*this, moved)) return xml_node();
  4739. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4740. if (!alloc.reserve()) return xml_node();
  4741. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4742. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4743. impl::remove_node(moved._root);
  4744. impl::append_node(moved._root, _root);
  4745. return moved;
  4746. }
  4747. PUGI__FN xml_node xml_node::prepend_move(const xml_node& moved)
  4748. {
  4749. if (!impl::allow_move(*this, moved)) return xml_node();
  4750. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4751. if (!alloc.reserve()) return xml_node();
  4752. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4753. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4754. impl::remove_node(moved._root);
  4755. impl::prepend_node(moved._root, _root);
  4756. return moved;
  4757. }
  4758. PUGI__FN xml_node xml_node::insert_move_after(const xml_node& moved, const xml_node& node)
  4759. {
  4760. if (!impl::allow_move(*this, moved)) return xml_node();
  4761. if (!node._root || node._root->parent != _root) return xml_node();
  4762. if (moved._root == node._root) return xml_node();
  4763. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4764. if (!alloc.reserve()) return xml_node();
  4765. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4766. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4767. impl::remove_node(moved._root);
  4768. impl::insert_node_after(moved._root, node._root);
  4769. return moved;
  4770. }
  4771. PUGI__FN xml_node xml_node::insert_move_before(const xml_node& moved, const xml_node& node)
  4772. {
  4773. if (!impl::allow_move(*this, moved)) return xml_node();
  4774. if (!node._root || node._root->parent != _root) return xml_node();
  4775. if (moved._root == node._root) return xml_node();
  4776. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4777. if (!alloc.reserve()) return xml_node();
  4778. // disable document_buffer_order optimization since moving nodes around changes document order without changing buffer pointers
  4779. impl::get_document(_root).header |= impl::xml_memory_page_contents_shared_mask;
  4780. impl::remove_node(moved._root);
  4781. impl::insert_node_before(moved._root, node._root);
  4782. return moved;
  4783. }
  4784. PUGI__FN bool xml_node::remove_attribute(const char_t* name_)
  4785. {
  4786. return remove_attribute(attribute(name_));
  4787. }
  4788. PUGI__FN bool xml_node::remove_attribute(const xml_attribute& a)
  4789. {
  4790. if (!_root || !a._attr) return false;
  4791. if (!impl::is_attribute_of(a._attr, _root)) return false;
  4792. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4793. if (!alloc.reserve()) return false;
  4794. impl::remove_attribute(a._attr, _root);
  4795. impl::destroy_attribute(a._attr, alloc);
  4796. return true;
  4797. }
  4798. PUGI__FN bool xml_node::remove_child(const char_t* name_)
  4799. {
  4800. return remove_child(child(name_));
  4801. }
  4802. PUGI__FN bool xml_node::remove_child(const xml_node& n)
  4803. {
  4804. if (!_root || !n._root || n._root->parent != _root) return false;
  4805. impl::xml_allocator& alloc = impl::get_allocator(_root);
  4806. if (!alloc.reserve()) return false;
  4807. impl::remove_node(n._root);
  4808. impl::destroy_node(n._root, alloc);
  4809. return true;
  4810. }
  4811. PUGI__FN xml_parse_result xml_node::append_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
  4812. {
  4813. // append_buffer is only valid for elements/documents
  4814. if (!impl::allow_insert_child(type(), node_element)) return impl::make_parse_result(status_append_invalid_root);
  4815. // get document node
  4816. impl::xml_document_struct* doc = &impl::get_document(_root);
  4817. // disable document_buffer_order optimization since in a document with multiple buffers comparing buffer pointers does not make sense
  4818. doc->header |= impl::xml_memory_page_contents_shared_mask;
  4819. // get extra buffer element (we'll store the document fragment buffer there so that we can deallocate it later)
  4820. impl::xml_memory_page* page = 0;
  4821. impl::xml_extra_buffer* extra = static_cast<impl::xml_extra_buffer*>(doc->allocate_memory(sizeof(impl::xml_extra_buffer) + sizeof(void*), page));
  4822. (void)page;
  4823. if (!extra) return impl::make_parse_result(status_out_of_memory);
  4824. #ifdef PUGIXML_COMPACT
  4825. // align the memory block to a pointer boundary; this is required for compact mode where memory allocations are only 4b aligned
  4826. // note that this requires up to sizeof(void*)-1 additional memory, which the allocation above takes into account
  4827. extra = reinterpret_cast<impl::xml_extra_buffer*>((reinterpret_cast<uintptr_t>(extra) + (sizeof(void*) - 1)) & ~(sizeof(void*) - 1));
  4828. #endif
  4829. // add extra buffer to the list
  4830. extra->buffer = 0;
  4831. extra->next = doc->extra_buffers;
  4832. doc->extra_buffers = extra;
  4833. // name of the root has to be NULL before parsing - otherwise closing node mismatches will not be detected at the top level
  4834. impl::name_null_sentry sentry(_root);
  4835. return impl::load_buffer_impl(doc, _root, const_cast<void*>(contents), size, options, encoding, false, false, &extra->buffer);
  4836. }
  4837. 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
  4838. {
  4839. if (!_root) return xml_node();
  4840. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4841. if (i->name && impl::strequal(name_, i->name))
  4842. {
  4843. for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
  4844. if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value + 0 : PUGIXML_TEXT("")))
  4845. return xml_node(i);
  4846. }
  4847. return xml_node();
  4848. }
  4849. PUGI__FN xml_node xml_node::find_child_by_attribute(const char_t* attr_name, const char_t* attr_value) const
  4850. {
  4851. if (!_root) return xml_node();
  4852. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  4853. for (xml_attribute_struct* a = i->first_attribute; a; a = a->next_attribute)
  4854. if (a->name && impl::strequal(attr_name, a->name) && impl::strequal(attr_value, a->value ? a->value + 0 : PUGIXML_TEXT("")))
  4855. return xml_node(i);
  4856. return xml_node();
  4857. }
  4858. #ifndef PUGIXML_NO_STL
  4859. PUGI__FN string_t xml_node::path(char_t delimiter) const
  4860. {
  4861. if (!_root) return string_t();
  4862. size_t offset = 0;
  4863. for (xml_node_struct* i = _root; i; i = i->parent)
  4864. {
  4865. offset += (i != _root);
  4866. offset += i->name ? impl::strlength(i->name) : 0;
  4867. }
  4868. string_t result;
  4869. result.resize(offset);
  4870. for (xml_node_struct* j = _root; j; j = j->parent)
  4871. {
  4872. if (j != _root)
  4873. result[--offset] = delimiter;
  4874. if (j->name)
  4875. {
  4876. size_t length = impl::strlength(j->name);
  4877. offset -= length;
  4878. memcpy(&result[offset], j->name, length * sizeof(char_t));
  4879. }
  4880. }
  4881. assert(offset == 0);
  4882. return result;
  4883. }
  4884. #endif
  4885. PUGI__FN xml_node xml_node::first_element_by_path(const char_t* path_, char_t delimiter) const
  4886. {
  4887. xml_node found = *this; // Current search context.
  4888. if (!_root || !path_[0]) return found;
  4889. if (path_[0] == delimiter)
  4890. {
  4891. // Absolute path; e.g. '/foo/bar'
  4892. found = found.root();
  4893. ++path_;
  4894. }
  4895. const char_t* path_segment = path_;
  4896. while (*path_segment == delimiter) ++path_segment;
  4897. const char_t* path_segment_end = path_segment;
  4898. while (*path_segment_end && *path_segment_end != delimiter) ++path_segment_end;
  4899. if (path_segment == path_segment_end) return found;
  4900. const char_t* next_segment = path_segment_end;
  4901. while (*next_segment == delimiter) ++next_segment;
  4902. if (*path_segment == '.' && path_segment + 1 == path_segment_end)
  4903. return found.first_element_by_path(next_segment, delimiter);
  4904. else if (*path_segment == '.' && *(path_segment+1) == '.' && path_segment + 2 == path_segment_end)
  4905. return found.parent().first_element_by_path(next_segment, delimiter);
  4906. else
  4907. {
  4908. for (xml_node_struct* j = found._root->first_child; j; j = j->next_sibling)
  4909. {
  4910. if (j->name && impl::strequalrange(j->name, path_segment, static_cast<size_t>(path_segment_end - path_segment)))
  4911. {
  4912. xml_node subsearch = xml_node(j).first_element_by_path(next_segment, delimiter);
  4913. if (subsearch) return subsearch;
  4914. }
  4915. }
  4916. return xml_node();
  4917. }
  4918. }
  4919. PUGI__FN bool xml_node::traverse(xml_tree_walker& walker)
  4920. {
  4921. walker._depth = -1;
  4922. xml_node arg_begin(_root);
  4923. if (!walker.begin(arg_begin)) return false;
  4924. xml_node_struct* cur = _root ? _root->first_child + 0 : 0;
  4925. if (cur)
  4926. {
  4927. ++walker._depth;
  4928. do
  4929. {
  4930. xml_node arg_for_each(cur);
  4931. if (!walker.for_each(arg_for_each))
  4932. return false;
  4933. if (cur->first_child)
  4934. {
  4935. ++walker._depth;
  4936. cur = cur->first_child;
  4937. }
  4938. else if (cur->next_sibling)
  4939. cur = cur->next_sibling;
  4940. else
  4941. {
  4942. while (!cur->next_sibling && cur != _root && cur->parent)
  4943. {
  4944. --walker._depth;
  4945. cur = cur->parent;
  4946. }
  4947. if (cur != _root)
  4948. cur = cur->next_sibling;
  4949. }
  4950. }
  4951. while (cur && cur != _root);
  4952. }
  4953. assert(walker._depth == -1);
  4954. xml_node arg_end(_root);
  4955. return walker.end(arg_end);
  4956. }
  4957. PUGI__FN size_t xml_node::hash_value() const
  4958. {
  4959. return static_cast<size_t>(reinterpret_cast<uintptr_t>(_root) / sizeof(xml_node_struct));
  4960. }
  4961. PUGI__FN xml_node_struct* xml_node::internal_object() const
  4962. {
  4963. return _root;
  4964. }
  4965. PUGI__FN void xml_node::print(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding, unsigned int depth) const
  4966. {
  4967. if (!_root) return;
  4968. impl::xml_buffered_writer buffered_writer(writer, encoding);
  4969. impl::node_output(buffered_writer, _root, indent, flags, depth);
  4970. buffered_writer.flush();
  4971. }
  4972. #ifndef PUGIXML_NO_STL
  4973. 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
  4974. {
  4975. xml_writer_stream writer(stream);
  4976. print(writer, indent, flags, encoding, depth);
  4977. }
  4978. 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
  4979. {
  4980. xml_writer_stream writer(stream);
  4981. print(writer, indent, flags, encoding_wchar, depth);
  4982. }
  4983. #endif
  4984. PUGI__FN ptrdiff_t xml_node::offset_debug() const
  4985. {
  4986. if (!_root) return -1;
  4987. impl::xml_document_struct& doc = impl::get_document(_root);
  4988. // we can determine the offset reliably only if there is exactly once parse buffer
  4989. if (!doc.buffer || doc.extra_buffers) return -1;
  4990. switch (type())
  4991. {
  4992. case node_document:
  4993. return 0;
  4994. case node_element:
  4995. case node_declaration:
  4996. case node_pi:
  4997. return _root->name && (_root->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0 ? _root->name - doc.buffer : -1;
  4998. case node_pcdata:
  4999. case node_cdata:
  5000. case node_comment:
  5001. case node_doctype:
  5002. return _root->value && (_root->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0 ? _root->value - doc.buffer : -1;
  5003. default:
  5004. assert(false && "Invalid node type"); // unreachable
  5005. return -1;
  5006. }
  5007. }
  5008. #ifdef __BORLANDC__
  5009. PUGI__FN bool operator&&(const xml_node& lhs, bool rhs)
  5010. {
  5011. return (bool)lhs && rhs;
  5012. }
  5013. PUGI__FN bool operator||(const xml_node& lhs, bool rhs)
  5014. {
  5015. return (bool)lhs || rhs;
  5016. }
  5017. #endif
  5018. PUGI__FN xml_text::xml_text(xml_node_struct* root): _root(root)
  5019. {
  5020. }
  5021. PUGI__FN xml_node_struct* xml_text::_data() const
  5022. {
  5023. if (!_root || impl::is_text_node(_root)) return _root;
  5024. // element nodes can have value if parse_embed_pcdata was used
  5025. if (PUGI__NODETYPE(_root) == node_element && _root->value)
  5026. return _root;
  5027. for (xml_node_struct* node = _root->first_child; node; node = node->next_sibling)
  5028. if (impl::is_text_node(node))
  5029. return node;
  5030. return 0;
  5031. }
  5032. PUGI__FN xml_node_struct* xml_text::_data_new()
  5033. {
  5034. xml_node_struct* d = _data();
  5035. if (d) return d;
  5036. return xml_node(_root).append_child(node_pcdata).internal_object();
  5037. }
  5038. PUGI__FN xml_text::xml_text(): _root(0)
  5039. {
  5040. }
  5041. PUGI__FN static void unspecified_bool_xml_text(xml_text***)
  5042. {
  5043. }
  5044. PUGI__FN xml_text::operator xml_text::unspecified_bool_type() const
  5045. {
  5046. return _data() ? unspecified_bool_xml_text : 0;
  5047. }
  5048. PUGI__FN bool xml_text::operator!() const
  5049. {
  5050. return !_data();
  5051. }
  5052. PUGI__FN bool xml_text::empty() const
  5053. {
  5054. return _data() == 0;
  5055. }
  5056. PUGI__FN const char_t* xml_text::get() const
  5057. {
  5058. xml_node_struct* d = _data();
  5059. return (d && d->value) ? d->value + 0 : PUGIXML_TEXT("");
  5060. }
  5061. PUGI__FN const char_t* xml_text::as_string(const char_t* def) const
  5062. {
  5063. xml_node_struct* d = _data();
  5064. return (d && d->value) ? d->value + 0 : def;
  5065. }
  5066. PUGI__FN int xml_text::as_int(int def) const
  5067. {
  5068. xml_node_struct* d = _data();
  5069. return (d && d->value) ? impl::get_value_int(d->value) : def;
  5070. }
  5071. PUGI__FN unsigned int xml_text::as_uint(unsigned int def) const
  5072. {
  5073. xml_node_struct* d = _data();
  5074. return (d && d->value) ? impl::get_value_uint(d->value) : def;
  5075. }
  5076. PUGI__FN double xml_text::as_double(double def) const
  5077. {
  5078. xml_node_struct* d = _data();
  5079. return (d && d->value) ? impl::get_value_double(d->value) : def;
  5080. }
  5081. PUGI__FN float xml_text::as_float(float def) const
  5082. {
  5083. xml_node_struct* d = _data();
  5084. return (d && d->value) ? impl::get_value_float(d->value) : def;
  5085. }
  5086. PUGI__FN bool xml_text::as_bool(bool def) const
  5087. {
  5088. xml_node_struct* d = _data();
  5089. return (d && d->value) ? impl::get_value_bool(d->value) : def;
  5090. }
  5091. #ifdef PUGIXML_HAS_LONG_LONG
  5092. PUGI__FN long long xml_text::as_llong(long long def) const
  5093. {
  5094. xml_node_struct* d = _data();
  5095. return (d && d->value) ? impl::get_value_llong(d->value) : def;
  5096. }
  5097. PUGI__FN unsigned long long xml_text::as_ullong(unsigned long long def) const
  5098. {
  5099. xml_node_struct* d = _data();
  5100. return (d && d->value) ? impl::get_value_ullong(d->value) : def;
  5101. }
  5102. #endif
  5103. PUGI__FN bool xml_text::set(const char_t* rhs)
  5104. {
  5105. xml_node_struct* dn = _data_new();
  5106. return dn ? impl::strcpy_insitu(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, impl::strlength(rhs)) : false;
  5107. }
  5108. PUGI__FN bool xml_text::set(int rhs)
  5109. {
  5110. xml_node_struct* dn = _data_new();
  5111. return dn ? impl::set_value_integer<unsigned int>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false;
  5112. }
  5113. PUGI__FN bool xml_text::set(unsigned int rhs)
  5114. {
  5115. xml_node_struct* dn = _data_new();
  5116. return dn ? impl::set_value_integer<unsigned int>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false;
  5117. }
  5118. PUGI__FN bool xml_text::set(long rhs)
  5119. {
  5120. xml_node_struct* dn = _data_new();
  5121. return dn ? impl::set_value_integer<unsigned long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false;
  5122. }
  5123. PUGI__FN bool xml_text::set(unsigned long rhs)
  5124. {
  5125. xml_node_struct* dn = _data_new();
  5126. return dn ? impl::set_value_integer<unsigned long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false;
  5127. }
  5128. PUGI__FN bool xml_text::set(float rhs)
  5129. {
  5130. xml_node_struct* dn = _data_new();
  5131. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  5132. }
  5133. PUGI__FN bool xml_text::set(double rhs)
  5134. {
  5135. xml_node_struct* dn = _data_new();
  5136. return dn ? impl::set_value_convert(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  5137. }
  5138. PUGI__FN bool xml_text::set(bool rhs)
  5139. {
  5140. xml_node_struct* dn = _data_new();
  5141. return dn ? impl::set_value_bool(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs) : false;
  5142. }
  5143. #ifdef PUGIXML_HAS_LONG_LONG
  5144. PUGI__FN bool xml_text::set(long long rhs)
  5145. {
  5146. xml_node_struct* dn = _data_new();
  5147. return dn ? impl::set_value_integer<unsigned long long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, rhs < 0) : false;
  5148. }
  5149. PUGI__FN bool xml_text::set(unsigned long long rhs)
  5150. {
  5151. xml_node_struct* dn = _data_new();
  5152. return dn ? impl::set_value_integer<unsigned long long>(dn->value, dn->header, impl::xml_memory_page_value_allocated_mask, rhs, false) : false;
  5153. }
  5154. #endif
  5155. PUGI__FN xml_text& xml_text::operator=(const char_t* rhs)
  5156. {
  5157. set(rhs);
  5158. return *this;
  5159. }
  5160. PUGI__FN xml_text& xml_text::operator=(int rhs)
  5161. {
  5162. set(rhs);
  5163. return *this;
  5164. }
  5165. PUGI__FN xml_text& xml_text::operator=(unsigned int rhs)
  5166. {
  5167. set(rhs);
  5168. return *this;
  5169. }
  5170. PUGI__FN xml_text& xml_text::operator=(long rhs)
  5171. {
  5172. set(rhs);
  5173. return *this;
  5174. }
  5175. PUGI__FN xml_text& xml_text::operator=(unsigned long rhs)
  5176. {
  5177. set(rhs);
  5178. return *this;
  5179. }
  5180. PUGI__FN xml_text& xml_text::operator=(double rhs)
  5181. {
  5182. set(rhs);
  5183. return *this;
  5184. }
  5185. PUGI__FN xml_text& xml_text::operator=(float rhs)
  5186. {
  5187. set(rhs);
  5188. return *this;
  5189. }
  5190. PUGI__FN xml_text& xml_text::operator=(bool rhs)
  5191. {
  5192. set(rhs);
  5193. return *this;
  5194. }
  5195. #ifdef PUGIXML_HAS_LONG_LONG
  5196. PUGI__FN xml_text& xml_text::operator=(long long rhs)
  5197. {
  5198. set(rhs);
  5199. return *this;
  5200. }
  5201. PUGI__FN xml_text& xml_text::operator=(unsigned long long rhs)
  5202. {
  5203. set(rhs);
  5204. return *this;
  5205. }
  5206. #endif
  5207. PUGI__FN xml_node xml_text::data() const
  5208. {
  5209. return xml_node(_data());
  5210. }
  5211. #ifdef __BORLANDC__
  5212. PUGI__FN bool operator&&(const xml_text& lhs, bool rhs)
  5213. {
  5214. return (bool)lhs && rhs;
  5215. }
  5216. PUGI__FN bool operator||(const xml_text& lhs, bool rhs)
  5217. {
  5218. return (bool)lhs || rhs;
  5219. }
  5220. #endif
  5221. PUGI__FN xml_node_iterator::xml_node_iterator()
  5222. {
  5223. }
  5224. PUGI__FN xml_node_iterator::xml_node_iterator(const xml_node& node): _wrap(node), _parent(node.parent())
  5225. {
  5226. }
  5227. PUGI__FN xml_node_iterator::xml_node_iterator(xml_node_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
  5228. {
  5229. }
  5230. PUGI__FN bool xml_node_iterator::operator==(const xml_node_iterator& rhs) const
  5231. {
  5232. return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
  5233. }
  5234. PUGI__FN bool xml_node_iterator::operator!=(const xml_node_iterator& rhs) const
  5235. {
  5236. return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
  5237. }
  5238. PUGI__FN xml_node& xml_node_iterator::operator*() const
  5239. {
  5240. assert(_wrap._root);
  5241. return _wrap;
  5242. }
  5243. PUGI__FN xml_node* xml_node_iterator::operator->() const
  5244. {
  5245. assert(_wrap._root);
  5246. return const_cast<xml_node*>(&_wrap); // BCC5 workaround
  5247. }
  5248. PUGI__FN const xml_node_iterator& xml_node_iterator::operator++()
  5249. {
  5250. assert(_wrap._root);
  5251. _wrap._root = _wrap._root->next_sibling;
  5252. return *this;
  5253. }
  5254. PUGI__FN xml_node_iterator xml_node_iterator::operator++(int)
  5255. {
  5256. xml_node_iterator temp = *this;
  5257. ++*this;
  5258. return temp;
  5259. }
  5260. PUGI__FN const xml_node_iterator& xml_node_iterator::operator--()
  5261. {
  5262. _wrap = _wrap._root ? _wrap.previous_sibling() : _parent.last_child();
  5263. return *this;
  5264. }
  5265. PUGI__FN xml_node_iterator xml_node_iterator::operator--(int)
  5266. {
  5267. xml_node_iterator temp = *this;
  5268. --*this;
  5269. return temp;
  5270. }
  5271. PUGI__FN xml_attribute_iterator::xml_attribute_iterator()
  5272. {
  5273. }
  5274. PUGI__FN xml_attribute_iterator::xml_attribute_iterator(const xml_attribute& attr, const xml_node& parent): _wrap(attr), _parent(parent)
  5275. {
  5276. }
  5277. PUGI__FN xml_attribute_iterator::xml_attribute_iterator(xml_attribute_struct* ref, xml_node_struct* parent): _wrap(ref), _parent(parent)
  5278. {
  5279. }
  5280. PUGI__FN bool xml_attribute_iterator::operator==(const xml_attribute_iterator& rhs) const
  5281. {
  5282. return _wrap._attr == rhs._wrap._attr && _parent._root == rhs._parent._root;
  5283. }
  5284. PUGI__FN bool xml_attribute_iterator::operator!=(const xml_attribute_iterator& rhs) const
  5285. {
  5286. return _wrap._attr != rhs._wrap._attr || _parent._root != rhs._parent._root;
  5287. }
  5288. PUGI__FN xml_attribute& xml_attribute_iterator::operator*() const
  5289. {
  5290. assert(_wrap._attr);
  5291. return _wrap;
  5292. }
  5293. PUGI__FN xml_attribute* xml_attribute_iterator::operator->() const
  5294. {
  5295. assert(_wrap._attr);
  5296. return const_cast<xml_attribute*>(&_wrap); // BCC5 workaround
  5297. }
  5298. PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator++()
  5299. {
  5300. assert(_wrap._attr);
  5301. _wrap._attr = _wrap._attr->next_attribute;
  5302. return *this;
  5303. }
  5304. PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator++(int)
  5305. {
  5306. xml_attribute_iterator temp = *this;
  5307. ++*this;
  5308. return temp;
  5309. }
  5310. PUGI__FN const xml_attribute_iterator& xml_attribute_iterator::operator--()
  5311. {
  5312. _wrap = _wrap._attr ? _wrap.previous_attribute() : _parent.last_attribute();
  5313. return *this;
  5314. }
  5315. PUGI__FN xml_attribute_iterator xml_attribute_iterator::operator--(int)
  5316. {
  5317. xml_attribute_iterator temp = *this;
  5318. --*this;
  5319. return temp;
  5320. }
  5321. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(): _name(0)
  5322. {
  5323. }
  5324. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(const xml_node& node, const char_t* name): _wrap(node), _parent(node.parent()), _name(name)
  5325. {
  5326. }
  5327. PUGI__FN xml_named_node_iterator::xml_named_node_iterator(xml_node_struct* ref, xml_node_struct* parent, const char_t* name): _wrap(ref), _parent(parent), _name(name)
  5328. {
  5329. }
  5330. PUGI__FN bool xml_named_node_iterator::operator==(const xml_named_node_iterator& rhs) const
  5331. {
  5332. return _wrap._root == rhs._wrap._root && _parent._root == rhs._parent._root;
  5333. }
  5334. PUGI__FN bool xml_named_node_iterator::operator!=(const xml_named_node_iterator& rhs) const
  5335. {
  5336. return _wrap._root != rhs._wrap._root || _parent._root != rhs._parent._root;
  5337. }
  5338. PUGI__FN xml_node& xml_named_node_iterator::operator*() const
  5339. {
  5340. assert(_wrap._root);
  5341. return _wrap;
  5342. }
  5343. PUGI__FN xml_node* xml_named_node_iterator::operator->() const
  5344. {
  5345. assert(_wrap._root);
  5346. return const_cast<xml_node*>(&_wrap); // BCC5 workaround
  5347. }
  5348. PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator++()
  5349. {
  5350. assert(_wrap._root);
  5351. _wrap = _wrap.next_sibling(_name);
  5352. return *this;
  5353. }
  5354. PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator++(int)
  5355. {
  5356. xml_named_node_iterator temp = *this;
  5357. ++*this;
  5358. return temp;
  5359. }
  5360. PUGI__FN const xml_named_node_iterator& xml_named_node_iterator::operator--()
  5361. {
  5362. if (_wrap._root)
  5363. _wrap = _wrap.previous_sibling(_name);
  5364. else
  5365. {
  5366. _wrap = _parent.last_child();
  5367. if (!impl::strequal(_wrap.name(), _name))
  5368. _wrap = _wrap.previous_sibling(_name);
  5369. }
  5370. return *this;
  5371. }
  5372. PUGI__FN xml_named_node_iterator xml_named_node_iterator::operator--(int)
  5373. {
  5374. xml_named_node_iterator temp = *this;
  5375. --*this;
  5376. return temp;
  5377. }
  5378. PUGI__FN xml_parse_result::xml_parse_result(): status(status_internal_error), offset(0), encoding(encoding_auto)
  5379. {
  5380. }
  5381. PUGI__FN xml_parse_result::operator bool() const
  5382. {
  5383. return status == status_ok;
  5384. }
  5385. PUGI__FN const char* xml_parse_result::description() const
  5386. {
  5387. switch (status)
  5388. {
  5389. case status_ok: return "No error";
  5390. case status_file_not_found: return "File was not found";
  5391. case status_io_error: return "Error reading from file/stream";
  5392. case status_out_of_memory: return "Could not allocate memory";
  5393. case status_internal_error: return "Internal error occurred";
  5394. case status_unrecognized_tag: return "Could not determine tag type";
  5395. case status_bad_pi: return "Error parsing document declaration/processing instruction";
  5396. case status_bad_comment: return "Error parsing comment";
  5397. case status_bad_cdata: return "Error parsing CDATA section";
  5398. case status_bad_doctype: return "Error parsing document type declaration";
  5399. case status_bad_pcdata: return "Error parsing PCDATA section";
  5400. case status_bad_start_element: return "Error parsing start element tag";
  5401. case status_bad_attribute: return "Error parsing element attribute";
  5402. case status_bad_end_element: return "Error parsing end element tag";
  5403. case status_end_element_mismatch: return "Start-end tags mismatch";
  5404. case status_append_invalid_root: return "Unable to append nodes: root is not an element or document";
  5405. case status_no_document_element: return "No document element found";
  5406. default: return "Unknown error";
  5407. }
  5408. }
  5409. PUGI__FN xml_document::xml_document(): _buffer(0)
  5410. {
  5411. _create();
  5412. }
  5413. PUGI__FN xml_document::~xml_document()
  5414. {
  5415. _destroy();
  5416. }
  5417. #ifdef PUGIXML_HAS_MOVE
  5418. PUGI__FN xml_document::xml_document(xml_document&& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT: _buffer(0)
  5419. {
  5420. _create();
  5421. _move(rhs);
  5422. }
  5423. PUGI__FN xml_document& xml_document::operator=(xml_document&& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT
  5424. {
  5425. if (this == &rhs) return *this;
  5426. _destroy();
  5427. _create();
  5428. _move(rhs);
  5429. return *this;
  5430. }
  5431. #endif
  5432. PUGI__FN void xml_document::reset()
  5433. {
  5434. _destroy();
  5435. _create();
  5436. }
  5437. PUGI__FN void xml_document::reset(const xml_document& proto)
  5438. {
  5439. reset();
  5440. for (xml_node cur = proto.first_child(); cur; cur = cur.next_sibling())
  5441. append_copy(cur);
  5442. }
  5443. PUGI__FN void xml_document::_create()
  5444. {
  5445. assert(!_root);
  5446. #ifdef PUGIXML_COMPACT
  5447. // space for page marker for the first page (uint32_t), rounded up to pointer size; assumes pointers are at least 32-bit
  5448. const size_t page_offset = sizeof(void*);
  5449. #else
  5450. const size_t page_offset = 0;
  5451. #endif
  5452. // initialize sentinel page
  5453. PUGI__STATIC_ASSERT(sizeof(impl::xml_memory_page) + sizeof(impl::xml_document_struct) + page_offset <= sizeof(_memory));
  5454. // prepare page structure
  5455. impl::xml_memory_page* page = impl::xml_memory_page::construct(_memory);
  5456. assert(page);
  5457. page->busy_size = impl::xml_memory_page_size;
  5458. // setup first page marker
  5459. #ifdef PUGIXML_COMPACT
  5460. // round-trip through void* to avoid 'cast increases required alignment of target type' warning
  5461. page->compact_page_marker = reinterpret_cast<uint32_t*>(static_cast<void*>(reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page)));
  5462. *page->compact_page_marker = sizeof(impl::xml_memory_page);
  5463. #endif
  5464. // allocate new root
  5465. _root = new (reinterpret_cast<char*>(page) + sizeof(impl::xml_memory_page) + page_offset) impl::xml_document_struct(page);
  5466. _root->prev_sibling_c = _root;
  5467. // setup sentinel page
  5468. page->allocator = static_cast<impl::xml_document_struct*>(_root);
  5469. // setup hash table pointer in allocator
  5470. #ifdef PUGIXML_COMPACT
  5471. page->allocator->_hash = &static_cast<impl::xml_document_struct*>(_root)->hash;
  5472. #endif
  5473. // verify the document allocation
  5474. assert(reinterpret_cast<char*>(_root) + sizeof(impl::xml_document_struct) <= _memory + sizeof(_memory));
  5475. }
  5476. PUGI__FN void xml_document::_destroy()
  5477. {
  5478. assert(_root);
  5479. // destroy static storage
  5480. if (_buffer)
  5481. {
  5482. impl::xml_memory::deallocate(_buffer);
  5483. _buffer = 0;
  5484. }
  5485. // destroy extra buffers (note: no need to destroy linked list nodes, they're allocated using document allocator)
  5486. for (impl::xml_extra_buffer* extra = static_cast<impl::xml_document_struct*>(_root)->extra_buffers; extra; extra = extra->next)
  5487. {
  5488. if (extra->buffer) impl::xml_memory::deallocate(extra->buffer);
  5489. }
  5490. // destroy dynamic storage, leave sentinel page (it's in static memory)
  5491. impl::xml_memory_page* root_page = PUGI__GETPAGE(_root);
  5492. assert(root_page && !root_page->prev);
  5493. assert(reinterpret_cast<char*>(root_page) >= _memory && reinterpret_cast<char*>(root_page) < _memory + sizeof(_memory));
  5494. for (impl::xml_memory_page* page = root_page->next; page; )
  5495. {
  5496. impl::xml_memory_page* next = page->next;
  5497. impl::xml_allocator::deallocate_page(page);
  5498. page = next;
  5499. }
  5500. #ifdef PUGIXML_COMPACT
  5501. // destroy hash table
  5502. static_cast<impl::xml_document_struct*>(_root)->hash.clear();
  5503. #endif
  5504. _root = 0;
  5505. }
  5506. #ifdef PUGIXML_HAS_MOVE
  5507. PUGI__FN void xml_document::_move(xml_document& rhs) PUGIXML_NOEXCEPT_IF_NOT_COMPACT
  5508. {
  5509. impl::xml_document_struct* doc = static_cast<impl::xml_document_struct*>(_root);
  5510. impl::xml_document_struct* other = static_cast<impl::xml_document_struct*>(rhs._root);
  5511. // save first child pointer for later; this needs hash access
  5512. xml_node_struct* other_first_child = other->first_child;
  5513. #ifdef PUGIXML_COMPACT
  5514. // reserve space for the hash table up front; this is the only operation that can fail
  5515. // if it does, we have no choice but to throw (if we have exceptions)
  5516. if (other_first_child)
  5517. {
  5518. size_t other_children = 0;
  5519. for (xml_node_struct* node = other_first_child; node; node = node->next_sibling)
  5520. other_children++;
  5521. // in compact mode, each pointer assignment could result in a hash table request
  5522. // during move, we have to relocate document first_child and parents of all children
  5523. // normally there's just one child and its parent has a pointerless encoding but
  5524. // we assume the worst here
  5525. if (!other->_hash->reserve(other_children + 1))
  5526. {
  5527. #ifdef PUGIXML_NO_EXCEPTIONS
  5528. return;
  5529. #else
  5530. throw std::bad_alloc();
  5531. #endif
  5532. }
  5533. }
  5534. #endif
  5535. // move allocation state
  5536. doc->_root = other->_root;
  5537. doc->_busy_size = other->_busy_size;
  5538. // move buffer state
  5539. doc->buffer = other->buffer;
  5540. doc->extra_buffers = other->extra_buffers;
  5541. _buffer = rhs._buffer;
  5542. #ifdef PUGIXML_COMPACT
  5543. // move compact hash; note that the hash table can have pointers to other but they will be "inactive", similarly to nodes removed with remove_child
  5544. doc->hash = other->hash;
  5545. doc->_hash = &doc->hash;
  5546. // make sure we don't access other hash up until the end when we reinitialize other document
  5547. other->_hash = 0;
  5548. #endif
  5549. // move page structure
  5550. impl::xml_memory_page* doc_page = PUGI__GETPAGE(doc);
  5551. assert(doc_page && !doc_page->prev && !doc_page->next);
  5552. impl::xml_memory_page* other_page = PUGI__GETPAGE(other);
  5553. assert(other_page && !other_page->prev);
  5554. // relink pages since root page is embedded into xml_document
  5555. if (impl::xml_memory_page* page = other_page->next)
  5556. {
  5557. assert(page->prev == other_page);
  5558. page->prev = doc_page;
  5559. doc_page->next = page;
  5560. other_page->next = 0;
  5561. }
  5562. // make sure pages point to the correct document state
  5563. for (impl::xml_memory_page* page = doc_page->next; page; page = page->next)
  5564. {
  5565. assert(page->allocator == other);
  5566. page->allocator = doc;
  5567. #ifdef PUGIXML_COMPACT
  5568. // this automatically migrates most children between documents and prevents ->parent assignment from allocating
  5569. if (page->compact_shared_parent == other)
  5570. page->compact_shared_parent = doc;
  5571. #endif
  5572. }
  5573. // move tree structure
  5574. assert(!doc->first_child);
  5575. doc->first_child = other_first_child;
  5576. for (xml_node_struct* node = other_first_child; node; node = node->next_sibling)
  5577. {
  5578. #ifdef PUGIXML_COMPACT
  5579. // most children will have migrated when we reassigned compact_shared_parent
  5580. assert(node->parent == other || node->parent == doc);
  5581. node->parent = doc;
  5582. #else
  5583. assert(node->parent == other);
  5584. node->parent = doc;
  5585. #endif
  5586. }
  5587. // reset other document
  5588. new (other) impl::xml_document_struct(PUGI__GETPAGE(other));
  5589. rhs._buffer = 0;
  5590. }
  5591. #endif
  5592. #ifndef PUGIXML_NO_STL
  5593. PUGI__FN xml_parse_result xml_document::load(std::basic_istream<char, std::char_traits<char> >& stream, unsigned int options, xml_encoding encoding)
  5594. {
  5595. reset();
  5596. return impl::load_stream_impl(static_cast<impl::xml_document_struct*>(_root), stream, options, encoding, &_buffer);
  5597. }
  5598. PUGI__FN xml_parse_result xml_document::load(std::basic_istream<wchar_t, std::char_traits<wchar_t> >& stream, unsigned int options)
  5599. {
  5600. reset();
  5601. return impl::load_stream_impl(static_cast<impl::xml_document_struct*>(_root), stream, options, encoding_wchar, &_buffer);
  5602. }
  5603. #endif
  5604. PUGI__FN xml_parse_result xml_document::load_string(const char_t* contents, unsigned int options)
  5605. {
  5606. // Force native encoding (skip autodetection)
  5607. #ifdef PUGIXML_WCHAR_MODE
  5608. xml_encoding encoding = encoding_wchar;
  5609. #else
  5610. xml_encoding encoding = encoding_utf8;
  5611. #endif
  5612. return load_buffer(contents, impl::strlength(contents) * sizeof(char_t), options, encoding);
  5613. }
  5614. PUGI__FN xml_parse_result xml_document::load(const char_t* contents, unsigned int options)
  5615. {
  5616. return load_string(contents, options);
  5617. }
  5618. PUGI__FN xml_parse_result xml_document::load_file(const char* path_, unsigned int options, xml_encoding encoding)
  5619. {
  5620. reset();
  5621. using impl::auto_deleter; // MSVC7 workaround
  5622. auto_deleter<FILE> file(fopen(path_, "rb"), impl::close_file);
  5623. return impl::load_file_impl(static_cast<impl::xml_document_struct*>(_root), file.data, options, encoding, &_buffer);
  5624. }
  5625. PUGI__FN xml_parse_result xml_document::load_file(const wchar_t* path_, unsigned int options, xml_encoding encoding)
  5626. {
  5627. reset();
  5628. using impl::auto_deleter; // MSVC7 workaround
  5629. auto_deleter<FILE> file(impl::open_file_wide(path_, L"rb"), impl::close_file);
  5630. return impl::load_file_impl(static_cast<impl::xml_document_struct*>(_root), file.data, options, encoding, &_buffer);
  5631. }
  5632. PUGI__FN xml_parse_result xml_document::load_buffer(const void* contents, size_t size, unsigned int options, xml_encoding encoding)
  5633. {
  5634. reset();
  5635. return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, const_cast<void*>(contents), size, options, encoding, false, false, &_buffer);
  5636. }
  5637. PUGI__FN xml_parse_result xml_document::load_buffer_inplace(void* contents, size_t size, unsigned int options, xml_encoding encoding)
  5638. {
  5639. reset();
  5640. return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, false, &_buffer);
  5641. }
  5642. PUGI__FN xml_parse_result xml_document::load_buffer_inplace_own(void* contents, size_t size, unsigned int options, xml_encoding encoding)
  5643. {
  5644. reset();
  5645. return impl::load_buffer_impl(static_cast<impl::xml_document_struct*>(_root), _root, contents, size, options, encoding, true, true, &_buffer);
  5646. }
  5647. PUGI__FN void xml_document::save(xml_writer& writer, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  5648. {
  5649. impl::xml_buffered_writer buffered_writer(writer, encoding);
  5650. if ((flags & format_write_bom) && encoding != encoding_latin1)
  5651. {
  5652. // BOM always represents the codepoint U+FEFF, so just write it in native encoding
  5653. #ifdef PUGIXML_WCHAR_MODE
  5654. unsigned int bom = 0xfeff;
  5655. buffered_writer.write(static_cast<wchar_t>(bom));
  5656. #else
  5657. buffered_writer.write('\xef', '\xbb', '\xbf');
  5658. #endif
  5659. }
  5660. if (!(flags & format_no_declaration) && !impl::has_declaration(_root))
  5661. {
  5662. buffered_writer.write_string(PUGIXML_TEXT("<?xml version=\"1.0\""));
  5663. if (encoding == encoding_latin1) buffered_writer.write_string(PUGIXML_TEXT(" encoding=\"ISO-8859-1\""));
  5664. buffered_writer.write('?', '>');
  5665. if (!(flags & format_raw)) buffered_writer.write('\n');
  5666. }
  5667. impl::node_output(buffered_writer, _root, indent, flags, 0);
  5668. buffered_writer.flush();
  5669. }
  5670. #ifndef PUGIXML_NO_STL
  5671. 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
  5672. {
  5673. xml_writer_stream writer(stream);
  5674. save(writer, indent, flags, encoding);
  5675. }
  5676. 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
  5677. {
  5678. xml_writer_stream writer(stream);
  5679. save(writer, indent, flags, encoding_wchar);
  5680. }
  5681. #endif
  5682. PUGI__FN bool xml_document::save_file(const char* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  5683. {
  5684. using impl::auto_deleter; // MSVC7 workaround
  5685. auto_deleter<FILE> file(fopen(path_, (flags & format_save_file_text) ? "w" : "wb"), impl::close_file);
  5686. return impl::save_file_impl(*this, file.data, indent, flags, encoding);
  5687. }
  5688. PUGI__FN bool xml_document::save_file(const wchar_t* path_, const char_t* indent, unsigned int flags, xml_encoding encoding) const
  5689. {
  5690. using impl::auto_deleter; // MSVC7 workaround
  5691. auto_deleter<FILE> file(impl::open_file_wide(path_, (flags & format_save_file_text) ? L"w" : L"wb"), impl::close_file);
  5692. return impl::save_file_impl(*this, file.data, indent, flags, encoding);
  5693. }
  5694. PUGI__FN xml_node xml_document::document_element() const
  5695. {
  5696. assert(_root);
  5697. for (xml_node_struct* i = _root->first_child; i; i = i->next_sibling)
  5698. if (PUGI__NODETYPE(i) == node_element)
  5699. return xml_node(i);
  5700. return xml_node();
  5701. }
  5702. #ifndef PUGIXML_NO_STL
  5703. PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const wchar_t* str)
  5704. {
  5705. assert(str);
  5706. return impl::as_utf8_impl(str, impl::strlength_wide(str));
  5707. }
  5708. PUGI__FN std::string PUGIXML_FUNCTION as_utf8(const std::basic_string<wchar_t>& str)
  5709. {
  5710. return impl::as_utf8_impl(str.c_str(), str.size());
  5711. }
  5712. PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const char* str)
  5713. {
  5714. assert(str);
  5715. return impl::as_wide_impl(str, strlen(str));
  5716. }
  5717. PUGI__FN std::basic_string<wchar_t> PUGIXML_FUNCTION as_wide(const std::string& str)
  5718. {
  5719. return impl::as_wide_impl(str.c_str(), str.size());
  5720. }
  5721. #endif
  5722. PUGI__FN void PUGIXML_FUNCTION set_memory_management_functions(allocation_function allocate, deallocation_function deallocate)
  5723. {
  5724. impl::xml_memory::allocate = allocate;
  5725. impl::xml_memory::deallocate = deallocate;
  5726. }
  5727. PUGI__FN allocation_function PUGIXML_FUNCTION get_memory_allocation_function()
  5728. {
  5729. return impl::xml_memory::allocate;
  5730. }
  5731. PUGI__FN deallocation_function PUGIXML_FUNCTION get_memory_deallocation_function()
  5732. {
  5733. return impl::xml_memory::deallocate;
  5734. }
  5735. }
  5736. #if !defined(PUGIXML_NO_STL) && (defined(_MSC_VER) || defined(__ICC))
  5737. namespace std
  5738. {
  5739. // Workarounds for (non-standard) iterator category detection for older versions (MSVC7/IC8 and earlier)
  5740. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_node_iterator&)
  5741. {
  5742. return std::bidirectional_iterator_tag();
  5743. }
  5744. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_attribute_iterator&)
  5745. {
  5746. return std::bidirectional_iterator_tag();
  5747. }
  5748. PUGI__FN std::bidirectional_iterator_tag _Iter_cat(const pugi::xml_named_node_iterator&)
  5749. {
  5750. return std::bidirectional_iterator_tag();
  5751. }
  5752. }
  5753. #endif
  5754. #if !defined(PUGIXML_NO_STL) && defined(__SUNPRO_CC)
  5755. namespace std
  5756. {
  5757. // Workarounds for (non-standard) iterator category detection
  5758. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_node_iterator&)
  5759. {
  5760. return std::bidirectional_iterator_tag();
  5761. }
  5762. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_attribute_iterator&)
  5763. {
  5764. return std::bidirectional_iterator_tag();
  5765. }
  5766. PUGI__FN std::bidirectional_iterator_tag __iterator_category(const pugi::xml_named_node_iterator&)
  5767. {
  5768. return std::bidirectional_iterator_tag();
  5769. }
  5770. }
  5771. #endif
  5772. #ifndef PUGIXML_NO_XPATH
  5773. // STL replacements
  5774. PUGI__NS_BEGIN
  5775. struct equal_to
  5776. {
  5777. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  5778. {
  5779. return lhs == rhs;
  5780. }
  5781. };
  5782. struct not_equal_to
  5783. {
  5784. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  5785. {
  5786. return lhs != rhs;
  5787. }
  5788. };
  5789. struct less
  5790. {
  5791. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  5792. {
  5793. return lhs < rhs;
  5794. }
  5795. };
  5796. struct less_equal
  5797. {
  5798. template <typename T> bool operator()(const T& lhs, const T& rhs) const
  5799. {
  5800. return lhs <= rhs;
  5801. }
  5802. };
  5803. template <typename T> inline void swap(T& lhs, T& rhs)
  5804. {
  5805. T temp = lhs;
  5806. lhs = rhs;
  5807. rhs = temp;
  5808. }
  5809. template <typename I, typename Pred> PUGI__FN I min_element(I begin, I end, const Pred& pred)
  5810. {
  5811. I result = begin;
  5812. for (I it = begin + 1; it != end; ++it)
  5813. if (pred(*it, *result))
  5814. result = it;
  5815. return result;
  5816. }
  5817. template <typename I> PUGI__FN void reverse(I begin, I end)
  5818. {
  5819. while (end - begin > 1)
  5820. swap(*begin++, *--end);
  5821. }
  5822. template <typename I> PUGI__FN I unique(I begin, I end)
  5823. {
  5824. // fast skip head
  5825. while (end - begin > 1 && *begin != *(begin + 1))
  5826. begin++;
  5827. if (begin == end)
  5828. return begin;
  5829. // last written element
  5830. I write = begin++;
  5831. // merge unique elements
  5832. while (begin != end)
  5833. {
  5834. if (*begin != *write)
  5835. *++write = *begin++;
  5836. else
  5837. begin++;
  5838. }
  5839. // past-the-end (write points to live element)
  5840. return write + 1;
  5841. }
  5842. template <typename T, typename Pred> PUGI__FN void insertion_sort(T* begin, T* end, const Pred& pred)
  5843. {
  5844. if (begin == end)
  5845. return;
  5846. for (T* it = begin + 1; it != end; ++it)
  5847. {
  5848. T val = *it;
  5849. T* hole = it;
  5850. // move hole backwards
  5851. while (hole > begin && pred(val, *(hole - 1)))
  5852. {
  5853. *hole = *(hole - 1);
  5854. hole--;
  5855. }
  5856. // fill hole with element
  5857. *hole = val;
  5858. }
  5859. }
  5860. template <typename I, typename Pred> inline I median3(I first, I middle, I last, const Pred& pred)
  5861. {
  5862. if (pred(*middle, *first))
  5863. swap(middle, first);
  5864. if (pred(*last, *middle))
  5865. swap(last, middle);
  5866. if (pred(*middle, *first))
  5867. swap(middle, first);
  5868. return middle;
  5869. }
  5870. template <typename T, typename Pred> PUGI__FN void partition3(T* begin, T* end, T pivot, const Pred& pred, T** out_eqbeg, T** out_eqend)
  5871. {
  5872. // invariant: array is split into 4 groups: = < ? > (each variable denotes the boundary between the groups)
  5873. T* eq = begin;
  5874. T* lt = begin;
  5875. T* gt = end;
  5876. while (lt < gt)
  5877. {
  5878. if (pred(*lt, pivot))
  5879. lt++;
  5880. else if (*lt == pivot)
  5881. swap(*eq++, *lt++);
  5882. else
  5883. swap(*lt, *--gt);
  5884. }
  5885. // we now have just 4 groups: = < >; move equal elements to the middle
  5886. T* eqbeg = gt;
  5887. for (T* it = begin; it != eq; ++it)
  5888. swap(*it, *--eqbeg);
  5889. *out_eqbeg = eqbeg;
  5890. *out_eqend = gt;
  5891. }
  5892. template <typename I, typename Pred> PUGI__FN void sort(I begin, I end, const Pred& pred)
  5893. {
  5894. // sort large chunks
  5895. while (end - begin > 16)
  5896. {
  5897. // find median element
  5898. I middle = begin + (end - begin) / 2;
  5899. I median = median3(begin, middle, end - 1, pred);
  5900. // partition in three chunks (< = >)
  5901. I eqbeg, eqend;
  5902. partition3(begin, end, *median, pred, &eqbeg, &eqend);
  5903. // loop on larger half
  5904. if (eqbeg - begin > end - eqend)
  5905. {
  5906. sort(eqend, end, pred);
  5907. end = eqbeg;
  5908. }
  5909. else
  5910. {
  5911. sort(begin, eqbeg, pred);
  5912. begin = eqend;
  5913. }
  5914. }
  5915. // insertion sort small chunk
  5916. insertion_sort(begin, end, pred);
  5917. }
  5918. PUGI__FN bool hash_insert(const void** table, size_t size, const void* key)
  5919. {
  5920. assert(key);
  5921. unsigned int h = static_cast<unsigned int>(reinterpret_cast<uintptr_t>(key));
  5922. // MurmurHash3 32-bit finalizer
  5923. h ^= h >> 16;
  5924. h *= 0x85ebca6bu;
  5925. h ^= h >> 13;
  5926. h *= 0xc2b2ae35u;
  5927. h ^= h >> 16;
  5928. size_t hashmod = size - 1;
  5929. size_t bucket = h & hashmod;
  5930. for (size_t probe = 0; probe <= hashmod; ++probe)
  5931. {
  5932. if (table[bucket] == 0)
  5933. {
  5934. table[bucket] = key;
  5935. return true;
  5936. }
  5937. if (table[bucket] == key)
  5938. return false;
  5939. // hash collision, quadratic probing
  5940. bucket = (bucket + probe + 1) & hashmod;
  5941. }
  5942. assert(false && "Hash table is full"); // unreachable
  5943. return false;
  5944. }
  5945. PUGI__NS_END
  5946. // Allocator used for AST and evaluation stacks
  5947. PUGI__NS_BEGIN
  5948. static const size_t xpath_memory_page_size =
  5949. #ifdef PUGIXML_MEMORY_XPATH_PAGE_SIZE
  5950. PUGIXML_MEMORY_XPATH_PAGE_SIZE
  5951. #else
  5952. 4096
  5953. #endif
  5954. ;
  5955. static const uintptr_t xpath_memory_block_alignment = sizeof(double) > sizeof(void*) ? sizeof(double) : sizeof(void*);
  5956. struct xpath_memory_block
  5957. {
  5958. xpath_memory_block* next;
  5959. size_t capacity;
  5960. union
  5961. {
  5962. char data[xpath_memory_page_size];
  5963. double alignment;
  5964. };
  5965. };
  5966. struct xpath_allocator
  5967. {
  5968. xpath_memory_block* _root;
  5969. size_t _root_size;
  5970. bool* _error;
  5971. xpath_allocator(xpath_memory_block* root, bool* error = 0): _root(root), _root_size(0), _error(error)
  5972. {
  5973. }
  5974. void* allocate(size_t size)
  5975. {
  5976. // round size up to block alignment boundary
  5977. size = (size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1);
  5978. if (_root_size + size <= _root->capacity)
  5979. {
  5980. void* buf = &_root->data[0] + _root_size;
  5981. _root_size += size;
  5982. return buf;
  5983. }
  5984. else
  5985. {
  5986. // make sure we have at least 1/4th of the page free after allocation to satisfy subsequent allocation requests
  5987. size_t block_capacity_base = sizeof(_root->data);
  5988. size_t block_capacity_req = size + block_capacity_base / 4;
  5989. size_t block_capacity = (block_capacity_base > block_capacity_req) ? block_capacity_base : block_capacity_req;
  5990. size_t block_size = block_capacity + offsetof(xpath_memory_block, data);
  5991. xpath_memory_block* block = static_cast<xpath_memory_block*>(xml_memory::allocate(block_size));
  5992. if (!block)
  5993. {
  5994. if (_error) *_error = true;
  5995. return 0;
  5996. }
  5997. block->next = _root;
  5998. block->capacity = block_capacity;
  5999. _root = block;
  6000. _root_size = size;
  6001. return block->data;
  6002. }
  6003. }
  6004. void* reallocate(void* ptr, size_t old_size, size_t new_size)
  6005. {
  6006. // round size up to block alignment boundary
  6007. old_size = (old_size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1);
  6008. new_size = (new_size + xpath_memory_block_alignment - 1) & ~(xpath_memory_block_alignment - 1);
  6009. // we can only reallocate the last object
  6010. assert(ptr == 0 || static_cast<char*>(ptr) + old_size == &_root->data[0] + _root_size);
  6011. // try to reallocate the object inplace
  6012. if (ptr && _root_size - old_size + new_size <= _root->capacity)
  6013. {
  6014. _root_size = _root_size - old_size + new_size;
  6015. return ptr;
  6016. }
  6017. // allocate a new block
  6018. void* result = allocate(new_size);
  6019. if (!result) return 0;
  6020. // we have a new block
  6021. if (ptr)
  6022. {
  6023. // copy old data (we only support growing)
  6024. assert(new_size >= old_size);
  6025. memcpy(result, ptr, old_size);
  6026. // free the previous page if it had no other objects
  6027. assert(_root->data == result);
  6028. assert(_root->next);
  6029. if (_root->next->data == ptr)
  6030. {
  6031. // deallocate the whole page, unless it was the first one
  6032. xpath_memory_block* next = _root->next->next;
  6033. if (next)
  6034. {
  6035. xml_memory::deallocate(_root->next);
  6036. _root->next = next;
  6037. }
  6038. }
  6039. }
  6040. return result;
  6041. }
  6042. void revert(const xpath_allocator& state)
  6043. {
  6044. // free all new pages
  6045. xpath_memory_block* cur = _root;
  6046. while (cur != state._root)
  6047. {
  6048. xpath_memory_block* next = cur->next;
  6049. xml_memory::deallocate(cur);
  6050. cur = next;
  6051. }
  6052. // restore state
  6053. _root = state._root;
  6054. _root_size = state._root_size;
  6055. }
  6056. void release()
  6057. {
  6058. xpath_memory_block* cur = _root;
  6059. assert(cur);
  6060. while (cur->next)
  6061. {
  6062. xpath_memory_block* next = cur->next;
  6063. xml_memory::deallocate(cur);
  6064. cur = next;
  6065. }
  6066. }
  6067. };
  6068. struct xpath_allocator_capture
  6069. {
  6070. xpath_allocator_capture(xpath_allocator* alloc): _target(alloc), _state(*alloc)
  6071. {
  6072. }
  6073. ~xpath_allocator_capture()
  6074. {
  6075. _target->revert(_state);
  6076. }
  6077. xpath_allocator* _target;
  6078. xpath_allocator _state;
  6079. };
  6080. struct xpath_stack
  6081. {
  6082. xpath_allocator* result;
  6083. xpath_allocator* temp;
  6084. };
  6085. struct xpath_stack_data
  6086. {
  6087. xpath_memory_block blocks[2];
  6088. xpath_allocator result;
  6089. xpath_allocator temp;
  6090. xpath_stack stack;
  6091. bool oom;
  6092. xpath_stack_data(): result(blocks + 0, &oom), temp(blocks + 1, &oom), oom(false)
  6093. {
  6094. blocks[0].next = blocks[1].next = 0;
  6095. blocks[0].capacity = blocks[1].capacity = sizeof(blocks[0].data);
  6096. stack.result = &result;
  6097. stack.temp = &temp;
  6098. }
  6099. ~xpath_stack_data()
  6100. {
  6101. result.release();
  6102. temp.release();
  6103. }
  6104. };
  6105. PUGI__NS_END
  6106. // String class
  6107. PUGI__NS_BEGIN
  6108. class xpath_string
  6109. {
  6110. const char_t* _buffer;
  6111. bool _uses_heap;
  6112. size_t _length_heap;
  6113. static char_t* duplicate_string(const char_t* string, size_t length, xpath_allocator* alloc)
  6114. {
  6115. char_t* result = static_cast<char_t*>(alloc->allocate((length + 1) * sizeof(char_t)));
  6116. if (!result) return 0;
  6117. memcpy(result, string, length * sizeof(char_t));
  6118. result[length] = 0;
  6119. return result;
  6120. }
  6121. xpath_string(const char_t* buffer, bool uses_heap_, size_t length_heap): _buffer(buffer), _uses_heap(uses_heap_), _length_heap(length_heap)
  6122. {
  6123. }
  6124. public:
  6125. static xpath_string from_const(const char_t* str)
  6126. {
  6127. return xpath_string(str, false, 0);
  6128. }
  6129. static xpath_string from_heap_preallocated(const char_t* begin, const char_t* end)
  6130. {
  6131. assert(begin <= end && *end == 0);
  6132. return xpath_string(begin, true, static_cast<size_t>(end - begin));
  6133. }
  6134. static xpath_string from_heap(const char_t* begin, const char_t* end, xpath_allocator* alloc)
  6135. {
  6136. assert(begin <= end);
  6137. if (begin == end)
  6138. return xpath_string();
  6139. size_t length = static_cast<size_t>(end - begin);
  6140. const char_t* data = duplicate_string(begin, length, alloc);
  6141. return data ? xpath_string(data, true, length) : xpath_string();
  6142. }
  6143. xpath_string(): _buffer(PUGIXML_TEXT("")), _uses_heap(false), _length_heap(0)
  6144. {
  6145. }
  6146. void append(const xpath_string& o, xpath_allocator* alloc)
  6147. {
  6148. // skip empty sources
  6149. if (!*o._buffer) return;
  6150. // fast append for constant empty target and constant source
  6151. if (!*_buffer && !_uses_heap && !o._uses_heap)
  6152. {
  6153. _buffer = o._buffer;
  6154. }
  6155. else
  6156. {
  6157. // need to make heap copy
  6158. size_t target_length = length();
  6159. size_t source_length = o.length();
  6160. size_t result_length = target_length + source_length;
  6161. // allocate new buffer
  6162. 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)));
  6163. if (!result) return;
  6164. // append first string to the new buffer in case there was no reallocation
  6165. if (!_uses_heap) memcpy(result, _buffer, target_length * sizeof(char_t));
  6166. // append second string to the new buffer
  6167. memcpy(result + target_length, o._buffer, source_length * sizeof(char_t));
  6168. result[result_length] = 0;
  6169. // finalize
  6170. _buffer = result;
  6171. _uses_heap = true;
  6172. _length_heap = result_length;
  6173. }
  6174. }
  6175. const char_t* c_str() const
  6176. {
  6177. return _buffer;
  6178. }
  6179. size_t length() const
  6180. {
  6181. return _uses_heap ? _length_heap : strlength(_buffer);
  6182. }
  6183. char_t* data(xpath_allocator* alloc)
  6184. {
  6185. // make private heap copy
  6186. if (!_uses_heap)
  6187. {
  6188. size_t length_ = strlength(_buffer);
  6189. const char_t* data_ = duplicate_string(_buffer, length_, alloc);
  6190. if (!data_) return 0;
  6191. _buffer = data_;
  6192. _uses_heap = true;
  6193. _length_heap = length_;
  6194. }
  6195. return const_cast<char_t*>(_buffer);
  6196. }
  6197. bool empty() const
  6198. {
  6199. return *_buffer == 0;
  6200. }
  6201. bool operator==(const xpath_string& o) const
  6202. {
  6203. return strequal(_buffer, o._buffer);
  6204. }
  6205. bool operator!=(const xpath_string& o) const
  6206. {
  6207. return !strequal(_buffer, o._buffer);
  6208. }
  6209. bool uses_heap() const
  6210. {
  6211. return _uses_heap;
  6212. }
  6213. };
  6214. PUGI__NS_END
  6215. PUGI__NS_BEGIN
  6216. PUGI__FN bool starts_with(const char_t* string, const char_t* pattern)
  6217. {
  6218. while (*pattern && *string == *pattern)
  6219. {
  6220. string++;
  6221. pattern++;
  6222. }
  6223. return *pattern == 0;
  6224. }
  6225. PUGI__FN const char_t* find_char(const char_t* s, char_t c)
  6226. {
  6227. #ifdef PUGIXML_WCHAR_MODE
  6228. return wcschr(s, c);
  6229. #else
  6230. return strchr(s, c);
  6231. #endif
  6232. }
  6233. PUGI__FN const char_t* find_substring(const char_t* s, const char_t* p)
  6234. {
  6235. #ifdef PUGIXML_WCHAR_MODE
  6236. // MSVC6 wcsstr bug workaround (if s is empty it always returns 0)
  6237. return (*p == 0) ? s : wcsstr(s, p);
  6238. #else
  6239. return strstr(s, p);
  6240. #endif
  6241. }
  6242. // Converts symbol to lower case, if it is an ASCII one
  6243. PUGI__FN char_t tolower_ascii(char_t ch)
  6244. {
  6245. return static_cast<unsigned int>(ch - 'A') < 26 ? static_cast<char_t>(ch | ' ') : ch;
  6246. }
  6247. PUGI__FN xpath_string string_value(const xpath_node& na, xpath_allocator* alloc)
  6248. {
  6249. if (na.attribute())
  6250. return xpath_string::from_const(na.attribute().value());
  6251. else
  6252. {
  6253. xml_node n = na.node();
  6254. switch (n.type())
  6255. {
  6256. case node_pcdata:
  6257. case node_cdata:
  6258. case node_comment:
  6259. case node_pi:
  6260. return xpath_string::from_const(n.value());
  6261. case node_document:
  6262. case node_element:
  6263. {
  6264. xpath_string result;
  6265. // element nodes can have value if parse_embed_pcdata was used
  6266. if (n.value()[0])
  6267. result.append(xpath_string::from_const(n.value()), alloc);
  6268. xml_node cur = n.first_child();
  6269. while (cur && cur != n)
  6270. {
  6271. if (cur.type() == node_pcdata || cur.type() == node_cdata)
  6272. result.append(xpath_string::from_const(cur.value()), alloc);
  6273. if (cur.first_child())
  6274. cur = cur.first_child();
  6275. else if (cur.next_sibling())
  6276. cur = cur.next_sibling();
  6277. else
  6278. {
  6279. while (!cur.next_sibling() && cur != n)
  6280. cur = cur.parent();
  6281. if (cur != n) cur = cur.next_sibling();
  6282. }
  6283. }
  6284. return result;
  6285. }
  6286. default:
  6287. return xpath_string();
  6288. }
  6289. }
  6290. }
  6291. PUGI__FN bool node_is_before_sibling(xml_node_struct* ln, xml_node_struct* rn)
  6292. {
  6293. assert(ln->parent == rn->parent);
  6294. // there is no common ancestor (the shared parent is null), nodes are from different documents
  6295. if (!ln->parent) return ln < rn;
  6296. // determine sibling order
  6297. xml_node_struct* ls = ln;
  6298. xml_node_struct* rs = rn;
  6299. while (ls && rs)
  6300. {
  6301. if (ls == rn) return true;
  6302. if (rs == ln) return false;
  6303. ls = ls->next_sibling;
  6304. rs = rs->next_sibling;
  6305. }
  6306. // if rn sibling chain ended ln must be before rn
  6307. return !rs;
  6308. }
  6309. PUGI__FN bool node_is_before(xml_node_struct* ln, xml_node_struct* rn)
  6310. {
  6311. // find common ancestor at the same depth, if any
  6312. xml_node_struct* lp = ln;
  6313. xml_node_struct* rp = rn;
  6314. while (lp && rp && lp->parent != rp->parent)
  6315. {
  6316. lp = lp->parent;
  6317. rp = rp->parent;
  6318. }
  6319. // parents are the same!
  6320. if (lp && rp) return node_is_before_sibling(lp, rp);
  6321. // nodes are at different depths, need to normalize heights
  6322. bool left_higher = !lp;
  6323. while (lp)
  6324. {
  6325. lp = lp->parent;
  6326. ln = ln->parent;
  6327. }
  6328. while (rp)
  6329. {
  6330. rp = rp->parent;
  6331. rn = rn->parent;
  6332. }
  6333. // one node is the ancestor of the other
  6334. if (ln == rn) return left_higher;
  6335. // find common ancestor... again
  6336. while (ln->parent != rn->parent)
  6337. {
  6338. ln = ln->parent;
  6339. rn = rn->parent;
  6340. }
  6341. return node_is_before_sibling(ln, rn);
  6342. }
  6343. PUGI__FN bool node_is_ancestor(xml_node_struct* parent, xml_node_struct* node)
  6344. {
  6345. while (node && node != parent) node = node->parent;
  6346. return parent && node == parent;
  6347. }
  6348. PUGI__FN const void* document_buffer_order(const xpath_node& xnode)
  6349. {
  6350. xml_node_struct* node = xnode.node().internal_object();
  6351. if (node)
  6352. {
  6353. if ((get_document(node).header & xml_memory_page_contents_shared_mask) == 0)
  6354. {
  6355. if (node->name && (node->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return node->name;
  6356. if (node->value && (node->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return node->value;
  6357. }
  6358. return 0;
  6359. }
  6360. xml_attribute_struct* attr = xnode.attribute().internal_object();
  6361. if (attr)
  6362. {
  6363. if ((get_document(attr).header & xml_memory_page_contents_shared_mask) == 0)
  6364. {
  6365. if ((attr->header & impl::xml_memory_page_name_allocated_or_shared_mask) == 0) return attr->name;
  6366. if ((attr->header & impl::xml_memory_page_value_allocated_or_shared_mask) == 0) return attr->value;
  6367. }
  6368. return 0;
  6369. }
  6370. return 0;
  6371. }
  6372. struct document_order_comparator
  6373. {
  6374. bool operator()(const xpath_node& lhs, const xpath_node& rhs) const
  6375. {
  6376. // optimized document order based check
  6377. const void* lo = document_buffer_order(lhs);
  6378. const void* ro = document_buffer_order(rhs);
  6379. if (lo && ro) return lo < ro;
  6380. // slow comparison
  6381. xml_node ln = lhs.node(), rn = rhs.node();
  6382. // compare attributes
  6383. if (lhs.attribute() && rhs.attribute())
  6384. {
  6385. // shared parent
  6386. if (lhs.parent() == rhs.parent())
  6387. {
  6388. // determine sibling order
  6389. for (xml_attribute a = lhs.attribute(); a; a = a.next_attribute())
  6390. if (a == rhs.attribute())
  6391. return true;
  6392. return false;
  6393. }
  6394. // compare attribute parents
  6395. ln = lhs.parent();
  6396. rn = rhs.parent();
  6397. }
  6398. else if (lhs.attribute())
  6399. {
  6400. // attributes go after the parent element
  6401. if (lhs.parent() == rhs.node()) return false;
  6402. ln = lhs.parent();
  6403. }
  6404. else if (rhs.attribute())
  6405. {
  6406. // attributes go after the parent element
  6407. if (rhs.parent() == lhs.node()) return true;
  6408. rn = rhs.parent();
  6409. }
  6410. if (ln == rn) return false;
  6411. if (!ln || !rn) return ln < rn;
  6412. return node_is_before(ln.internal_object(), rn.internal_object());
  6413. }
  6414. };
  6415. PUGI__FN double gen_nan()
  6416. {
  6417. #if defined(__STDC_IEC_559__) || ((FLT_RADIX - 0 == 2) && (FLT_MAX_EXP - 0 == 128) && (FLT_MANT_DIG - 0 == 24))
  6418. PUGI__STATIC_ASSERT(sizeof(float) == sizeof(uint32_t));
  6419. typedef uint32_t UI; // BCC5 workaround
  6420. union { float f; UI i; } u;
  6421. u.i = 0x7fc00000;
  6422. return double(u.f);
  6423. #else
  6424. // fallback
  6425. const volatile double zero = 0.0;
  6426. return zero / zero;
  6427. #endif
  6428. }
  6429. PUGI__FN bool is_nan(double value)
  6430. {
  6431. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
  6432. return !!_isnan(value);
  6433. #elif defined(fpclassify) && defined(FP_NAN)
  6434. return fpclassify(value) == FP_NAN;
  6435. #else
  6436. // fallback
  6437. const volatile double v = value;
  6438. return v != v;
  6439. #endif
  6440. }
  6441. PUGI__FN const char_t* convert_number_to_string_special(double value)
  6442. {
  6443. #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__)
  6444. if (_finite(value)) return (value == 0) ? PUGIXML_TEXT("0") : 0;
  6445. if (_isnan(value)) return PUGIXML_TEXT("NaN");
  6446. return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  6447. #elif defined(fpclassify) && defined(FP_NAN) && defined(FP_INFINITE) && defined(FP_ZERO)
  6448. switch (fpclassify(value))
  6449. {
  6450. case FP_NAN:
  6451. return PUGIXML_TEXT("NaN");
  6452. case FP_INFINITE:
  6453. return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  6454. case FP_ZERO:
  6455. return PUGIXML_TEXT("0");
  6456. default:
  6457. return 0;
  6458. }
  6459. #else
  6460. // fallback
  6461. const volatile double v = value;
  6462. if (v == 0) return PUGIXML_TEXT("0");
  6463. if (v != v) return PUGIXML_TEXT("NaN");
  6464. if (v * 2 == v) return value > 0 ? PUGIXML_TEXT("Infinity") : PUGIXML_TEXT("-Infinity");
  6465. return 0;
  6466. #endif
  6467. }
  6468. PUGI__FN bool convert_number_to_boolean(double value)
  6469. {
  6470. return (value != 0 && !is_nan(value));
  6471. }
  6472. PUGI__FN void truncate_zeros(char* begin, char* end)
  6473. {
  6474. while (begin != end && end[-1] == '0') end--;
  6475. *end = 0;
  6476. }
  6477. // gets mantissa digits in the form of 0.xxxxx with 0. implied and the exponent
  6478. #if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
  6479. PUGI__FN void convert_number_to_mantissa_exponent(double value, char (&buffer)[32], char** out_mantissa, int* out_exponent)
  6480. {
  6481. // get base values
  6482. int sign, exponent;
  6483. _ecvt_s(buffer, sizeof(buffer), value, DBL_DIG + 1, &exponent, &sign);
  6484. // truncate redundant zeros
  6485. truncate_zeros(buffer, buffer + strlen(buffer));
  6486. // fill results
  6487. *out_mantissa = buffer;
  6488. *out_exponent = exponent;
  6489. }
  6490. #else
  6491. PUGI__FN void convert_number_to_mantissa_exponent(double value, char (&buffer)[32], char** out_mantissa, int* out_exponent)
  6492. {
  6493. // get a scientific notation value with IEEE DBL_DIG decimals
  6494. PUGI__SNPRINTF(buffer, "%.*e", DBL_DIG, value);
  6495. // get the exponent (possibly negative)
  6496. char* exponent_string = strchr(buffer, 'e');
  6497. assert(exponent_string);
  6498. int exponent = atoi(exponent_string + 1);
  6499. // extract mantissa string: skip sign
  6500. char* mantissa = buffer[0] == '-' ? buffer + 1 : buffer;
  6501. assert(mantissa[0] != '0' && mantissa[1] == '.');
  6502. // divide mantissa by 10 to eliminate integer part
  6503. mantissa[1] = mantissa[0];
  6504. mantissa++;
  6505. exponent++;
  6506. // remove extra mantissa digits and zero-terminate mantissa
  6507. truncate_zeros(mantissa, exponent_string);
  6508. // fill results
  6509. *out_mantissa = mantissa;
  6510. *out_exponent = exponent;
  6511. }
  6512. #endif
  6513. PUGI__FN xpath_string convert_number_to_string(double value, xpath_allocator* alloc)
  6514. {
  6515. // try special number conversion
  6516. const char_t* special = convert_number_to_string_special(value);
  6517. if (special) return xpath_string::from_const(special);
  6518. // get mantissa + exponent form
  6519. char mantissa_buffer[32];
  6520. char* mantissa;
  6521. int exponent;
  6522. convert_number_to_mantissa_exponent(value, mantissa_buffer, &mantissa, &exponent);
  6523. // allocate a buffer of suitable length for the number
  6524. size_t result_size = strlen(mantissa_buffer) + (exponent > 0 ? exponent : -exponent) + 4;
  6525. char_t* result = static_cast<char_t*>(alloc->allocate(sizeof(char_t) * result_size));
  6526. if (!result) return xpath_string();
  6527. // make the number!
  6528. char_t* s = result;
  6529. // sign
  6530. if (value < 0) *s++ = '-';
  6531. // integer part
  6532. if (exponent <= 0)
  6533. {
  6534. *s++ = '0';
  6535. }
  6536. else
  6537. {
  6538. while (exponent > 0)
  6539. {
  6540. assert(*mantissa == 0 || static_cast<unsigned int>(*mantissa - '0') <= 9);
  6541. *s++ = *mantissa ? *mantissa++ : '0';
  6542. exponent--;
  6543. }
  6544. }
  6545. // fractional part
  6546. if (*mantissa)
  6547. {
  6548. // decimal point
  6549. *s++ = '.';
  6550. // extra zeroes from negative exponent
  6551. while (exponent < 0)
  6552. {
  6553. *s++ = '0';
  6554. exponent++;
  6555. }
  6556. // extra mantissa digits
  6557. while (*mantissa)
  6558. {
  6559. assert(static_cast<unsigned int>(*mantissa - '0') <= 9);
  6560. *s++ = *mantissa++;
  6561. }
  6562. }
  6563. // zero-terminate
  6564. assert(s < result + result_size);
  6565. *s = 0;
  6566. return xpath_string::from_heap_preallocated(result, s);
  6567. }
  6568. PUGI__FN bool check_string_to_number_format(const char_t* string)
  6569. {
  6570. // parse leading whitespace
  6571. while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
  6572. // parse sign
  6573. if (*string == '-') ++string;
  6574. if (!*string) return false;
  6575. // if there is no integer part, there should be a decimal part with at least one digit
  6576. if (!PUGI__IS_CHARTYPEX(string[0], ctx_digit) && (string[0] != '.' || !PUGI__IS_CHARTYPEX(string[1], ctx_digit))) return false;
  6577. // parse integer part
  6578. while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
  6579. // parse decimal part
  6580. if (*string == '.')
  6581. {
  6582. ++string;
  6583. while (PUGI__IS_CHARTYPEX(*string, ctx_digit)) ++string;
  6584. }
  6585. // parse trailing whitespace
  6586. while (PUGI__IS_CHARTYPE(*string, ct_space)) ++string;
  6587. return *string == 0;
  6588. }
  6589. PUGI__FN double convert_string_to_number(const char_t* string)
  6590. {
  6591. // check string format
  6592. if (!check_string_to_number_format(string)) return gen_nan();
  6593. // parse string
  6594. #ifdef PUGIXML_WCHAR_MODE
  6595. return wcstod(string, 0);
  6596. #else
  6597. return strtod(string, 0);
  6598. #endif
  6599. }
  6600. PUGI__FN bool convert_string_to_number_scratch(char_t (&buffer)[32], const char_t* begin, const char_t* end, double* out_result)
  6601. {
  6602. size_t length = static_cast<size_t>(end - begin);
  6603. char_t* scratch = buffer;
  6604. if (length >= sizeof(buffer) / sizeof(buffer[0]))
  6605. {
  6606. // need to make dummy on-heap copy
  6607. scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  6608. if (!scratch) return false;
  6609. }
  6610. // copy string to zero-terminated buffer and perform conversion
  6611. memcpy(scratch, begin, length * sizeof(char_t));
  6612. scratch[length] = 0;
  6613. *out_result = convert_string_to_number(scratch);
  6614. // free dummy buffer
  6615. if (scratch != buffer) xml_memory::deallocate(scratch);
  6616. return true;
  6617. }
  6618. PUGI__FN double round_nearest(double value)
  6619. {
  6620. return floor(value + 0.5);
  6621. }
  6622. PUGI__FN double round_nearest_nzero(double value)
  6623. {
  6624. // same as round_nearest, but returns -0 for [-0.5, -0]
  6625. // ceil is used to differentiate between +0 and -0 (we return -0 for [-0.5, -0] and +0 for +0)
  6626. return (value >= -0.5 && value <= 0) ? ceil(value) : floor(value + 0.5);
  6627. }
  6628. PUGI__FN const char_t* qualified_name(const xpath_node& node)
  6629. {
  6630. return node.attribute() ? node.attribute().name() : node.node().name();
  6631. }
  6632. PUGI__FN const char_t* local_name(const xpath_node& node)
  6633. {
  6634. const char_t* name = qualified_name(node);
  6635. const char_t* p = find_char(name, ':');
  6636. return p ? p + 1 : name;
  6637. }
  6638. struct namespace_uri_predicate
  6639. {
  6640. const char_t* prefix;
  6641. size_t prefix_length;
  6642. namespace_uri_predicate(const char_t* name)
  6643. {
  6644. const char_t* pos = find_char(name, ':');
  6645. prefix = pos ? name : 0;
  6646. prefix_length = pos ? static_cast<size_t>(pos - name) : 0;
  6647. }
  6648. bool operator()(xml_attribute a) const
  6649. {
  6650. const char_t* name = a.name();
  6651. if (!starts_with(name, PUGIXML_TEXT("xmlns"))) return false;
  6652. return prefix ? name[5] == ':' && strequalrange(name + 6, prefix, prefix_length) : name[5] == 0;
  6653. }
  6654. };
  6655. PUGI__FN const char_t* namespace_uri(xml_node node)
  6656. {
  6657. namespace_uri_predicate pred = node.name();
  6658. xml_node p = node;
  6659. while (p)
  6660. {
  6661. xml_attribute a = p.find_attribute(pred);
  6662. if (a) return a.value();
  6663. p = p.parent();
  6664. }
  6665. return PUGIXML_TEXT("");
  6666. }
  6667. PUGI__FN const char_t* namespace_uri(xml_attribute attr, xml_node parent)
  6668. {
  6669. namespace_uri_predicate pred = attr.name();
  6670. // Default namespace does not apply to attributes
  6671. if (!pred.prefix) return PUGIXML_TEXT("");
  6672. xml_node p = parent;
  6673. while (p)
  6674. {
  6675. xml_attribute a = p.find_attribute(pred);
  6676. if (a) return a.value();
  6677. p = p.parent();
  6678. }
  6679. return PUGIXML_TEXT("");
  6680. }
  6681. PUGI__FN const char_t* namespace_uri(const xpath_node& node)
  6682. {
  6683. return node.attribute() ? namespace_uri(node.attribute(), node.parent()) : namespace_uri(node.node());
  6684. }
  6685. PUGI__FN char_t* normalize_space(char_t* buffer)
  6686. {
  6687. char_t* write = buffer;
  6688. for (char_t* it = buffer; *it; )
  6689. {
  6690. char_t ch = *it++;
  6691. if (PUGI__IS_CHARTYPE(ch, ct_space))
  6692. {
  6693. // replace whitespace sequence with single space
  6694. while (PUGI__IS_CHARTYPE(*it, ct_space)) it++;
  6695. // avoid leading spaces
  6696. if (write != buffer) *write++ = ' ';
  6697. }
  6698. else *write++ = ch;
  6699. }
  6700. // remove trailing space
  6701. if (write != buffer && PUGI__IS_CHARTYPE(write[-1], ct_space)) write--;
  6702. // zero-terminate
  6703. *write = 0;
  6704. return write;
  6705. }
  6706. PUGI__FN char_t* translate(char_t* buffer, const char_t* from, const char_t* to, size_t to_length)
  6707. {
  6708. char_t* write = buffer;
  6709. while (*buffer)
  6710. {
  6711. PUGI__DMC_VOLATILE char_t ch = *buffer++;
  6712. const char_t* pos = find_char(from, ch);
  6713. if (!pos)
  6714. *write++ = ch; // do not process
  6715. else if (static_cast<size_t>(pos - from) < to_length)
  6716. *write++ = to[pos - from]; // replace
  6717. }
  6718. // zero-terminate
  6719. *write = 0;
  6720. return write;
  6721. }
  6722. PUGI__FN unsigned char* translate_table_generate(xpath_allocator* alloc, const char_t* from, const char_t* to)
  6723. {
  6724. unsigned char table[128] = {0};
  6725. while (*from)
  6726. {
  6727. unsigned int fc = static_cast<unsigned int>(*from);
  6728. unsigned int tc = static_cast<unsigned int>(*to);
  6729. if (fc >= 128 || tc >= 128)
  6730. return 0;
  6731. // code=128 means "skip character"
  6732. if (!table[fc])
  6733. table[fc] = static_cast<unsigned char>(tc ? tc : 128);
  6734. from++;
  6735. if (tc) to++;
  6736. }
  6737. for (int i = 0; i < 128; ++i)
  6738. if (!table[i])
  6739. table[i] = static_cast<unsigned char>(i);
  6740. void* result = alloc->allocate(sizeof(table));
  6741. if (!result) return 0;
  6742. memcpy(result, table, sizeof(table));
  6743. return static_cast<unsigned char*>(result);
  6744. }
  6745. PUGI__FN char_t* translate_table(char_t* buffer, const unsigned char* table)
  6746. {
  6747. char_t* write = buffer;
  6748. while (*buffer)
  6749. {
  6750. char_t ch = *buffer++;
  6751. unsigned int index = static_cast<unsigned int>(ch);
  6752. if (index < 128)
  6753. {
  6754. unsigned char code = table[index];
  6755. // code=128 means "skip character" (table size is 128 so 128 can be a special value)
  6756. // this code skips these characters without extra branches
  6757. *write = static_cast<char_t>(code);
  6758. write += 1 - (code >> 7);
  6759. }
  6760. else
  6761. {
  6762. *write++ = ch;
  6763. }
  6764. }
  6765. // zero-terminate
  6766. *write = 0;
  6767. return write;
  6768. }
  6769. inline bool is_xpath_attribute(const char_t* name)
  6770. {
  6771. return !(starts_with(name, PUGIXML_TEXT("xmlns")) && (name[5] == 0 || name[5] == ':'));
  6772. }
  6773. struct xpath_variable_boolean: xpath_variable
  6774. {
  6775. xpath_variable_boolean(): xpath_variable(xpath_type_boolean), value(false)
  6776. {
  6777. }
  6778. bool value;
  6779. char_t name[1];
  6780. };
  6781. struct xpath_variable_number: xpath_variable
  6782. {
  6783. xpath_variable_number(): xpath_variable(xpath_type_number), value(0)
  6784. {
  6785. }
  6786. double value;
  6787. char_t name[1];
  6788. };
  6789. struct xpath_variable_string: xpath_variable
  6790. {
  6791. xpath_variable_string(): xpath_variable(xpath_type_string), value(0)
  6792. {
  6793. }
  6794. ~xpath_variable_string()
  6795. {
  6796. if (value) xml_memory::deallocate(value);
  6797. }
  6798. char_t* value;
  6799. char_t name[1];
  6800. };
  6801. struct xpath_variable_node_set: xpath_variable
  6802. {
  6803. xpath_variable_node_set(): xpath_variable(xpath_type_node_set)
  6804. {
  6805. }
  6806. xpath_node_set value;
  6807. char_t name[1];
  6808. };
  6809. static const xpath_node_set dummy_node_set;
  6810. PUGI__FN PUGI__UNSIGNED_OVERFLOW unsigned int hash_string(const char_t* str)
  6811. {
  6812. // Jenkins one-at-a-time hash (http://en.wikipedia.org/wiki/Jenkins_hash_function#one-at-a-time)
  6813. unsigned int result = 0;
  6814. while (*str)
  6815. {
  6816. result += static_cast<unsigned int>(*str++);
  6817. result += result << 10;
  6818. result ^= result >> 6;
  6819. }
  6820. result += result << 3;
  6821. result ^= result >> 11;
  6822. result += result << 15;
  6823. return result;
  6824. }
  6825. template <typename T> PUGI__FN T* new_xpath_variable(const char_t* name)
  6826. {
  6827. size_t length = strlength(name);
  6828. if (length == 0) return 0; // empty variable names are invalid
  6829. // $$ we can't use offsetof(T, name) because T is non-POD, so we just allocate additional length characters
  6830. void* memory = xml_memory::allocate(sizeof(T) + length * sizeof(char_t));
  6831. if (!memory) return 0;
  6832. T* result = new (memory) T();
  6833. memcpy(result->name, name, (length + 1) * sizeof(char_t));
  6834. return result;
  6835. }
  6836. PUGI__FN xpath_variable* new_xpath_variable(xpath_value_type type, const char_t* name)
  6837. {
  6838. switch (type)
  6839. {
  6840. case xpath_type_node_set:
  6841. return new_xpath_variable<xpath_variable_node_set>(name);
  6842. case xpath_type_number:
  6843. return new_xpath_variable<xpath_variable_number>(name);
  6844. case xpath_type_string:
  6845. return new_xpath_variable<xpath_variable_string>(name);
  6846. case xpath_type_boolean:
  6847. return new_xpath_variable<xpath_variable_boolean>(name);
  6848. default:
  6849. return 0;
  6850. }
  6851. }
  6852. template <typename T> PUGI__FN void delete_xpath_variable(T* var)
  6853. {
  6854. var->~T();
  6855. xml_memory::deallocate(var);
  6856. }
  6857. PUGI__FN void delete_xpath_variable(xpath_value_type type, xpath_variable* var)
  6858. {
  6859. switch (type)
  6860. {
  6861. case xpath_type_node_set:
  6862. delete_xpath_variable(static_cast<xpath_variable_node_set*>(var));
  6863. break;
  6864. case xpath_type_number:
  6865. delete_xpath_variable(static_cast<xpath_variable_number*>(var));
  6866. break;
  6867. case xpath_type_string:
  6868. delete_xpath_variable(static_cast<xpath_variable_string*>(var));
  6869. break;
  6870. case xpath_type_boolean:
  6871. delete_xpath_variable(static_cast<xpath_variable_boolean*>(var));
  6872. break;
  6873. default:
  6874. assert(false && "Invalid variable type"); // unreachable
  6875. }
  6876. }
  6877. PUGI__FN bool copy_xpath_variable(xpath_variable* lhs, const xpath_variable* rhs)
  6878. {
  6879. switch (rhs->type())
  6880. {
  6881. case xpath_type_node_set:
  6882. return lhs->set(static_cast<const xpath_variable_node_set*>(rhs)->value);
  6883. case xpath_type_number:
  6884. return lhs->set(static_cast<const xpath_variable_number*>(rhs)->value);
  6885. case xpath_type_string:
  6886. return lhs->set(static_cast<const xpath_variable_string*>(rhs)->value);
  6887. case xpath_type_boolean:
  6888. return lhs->set(static_cast<const xpath_variable_boolean*>(rhs)->value);
  6889. default:
  6890. assert(false && "Invalid variable type"); // unreachable
  6891. return false;
  6892. }
  6893. }
  6894. PUGI__FN bool get_variable_scratch(char_t (&buffer)[32], xpath_variable_set* set, const char_t* begin, const char_t* end, xpath_variable** out_result)
  6895. {
  6896. size_t length = static_cast<size_t>(end - begin);
  6897. char_t* scratch = buffer;
  6898. if (length >= sizeof(buffer) / sizeof(buffer[0]))
  6899. {
  6900. // need to make dummy on-heap copy
  6901. scratch = static_cast<char_t*>(xml_memory::allocate((length + 1) * sizeof(char_t)));
  6902. if (!scratch) return false;
  6903. }
  6904. // copy string to zero-terminated buffer and perform lookup
  6905. memcpy(scratch, begin, length * sizeof(char_t));
  6906. scratch[length] = 0;
  6907. *out_result = set->get(scratch);
  6908. // free dummy buffer
  6909. if (scratch != buffer) xml_memory::deallocate(scratch);
  6910. return true;
  6911. }
  6912. PUGI__NS_END
  6913. // Internal node set class
  6914. PUGI__NS_BEGIN
  6915. PUGI__FN xpath_node_set::type_t xpath_get_order(const xpath_node* begin, const xpath_node* end)
  6916. {
  6917. if (end - begin < 2)
  6918. return xpath_node_set::type_sorted;
  6919. document_order_comparator cmp;
  6920. bool first = cmp(begin[0], begin[1]);
  6921. for (const xpath_node* it = begin + 1; it + 1 < end; ++it)
  6922. if (cmp(it[0], it[1]) != first)
  6923. return xpath_node_set::type_unsorted;
  6924. return first ? xpath_node_set::type_sorted : xpath_node_set::type_sorted_reverse;
  6925. }
  6926. PUGI__FN xpath_node_set::type_t xpath_sort(xpath_node* begin, xpath_node* end, xpath_node_set::type_t type, bool rev)
  6927. {
  6928. xpath_node_set::type_t order = rev ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
  6929. if (type == xpath_node_set::type_unsorted)
  6930. {
  6931. xpath_node_set::type_t sorted = xpath_get_order(begin, end);
  6932. if (sorted == xpath_node_set::type_unsorted)
  6933. {
  6934. sort(begin, end, document_order_comparator());
  6935. type = xpath_node_set::type_sorted;
  6936. }
  6937. else
  6938. type = sorted;
  6939. }
  6940. if (type != order) reverse(begin, end);
  6941. return order;
  6942. }
  6943. PUGI__FN xpath_node xpath_first(const xpath_node* begin, const xpath_node* end, xpath_node_set::type_t type)
  6944. {
  6945. if (begin == end) return xpath_node();
  6946. switch (type)
  6947. {
  6948. case xpath_node_set::type_sorted:
  6949. return *begin;
  6950. case xpath_node_set::type_sorted_reverse:
  6951. return *(end - 1);
  6952. case xpath_node_set::type_unsorted:
  6953. return *min_element(begin, end, document_order_comparator());
  6954. default:
  6955. assert(false && "Invalid node set type"); // unreachable
  6956. return xpath_node();
  6957. }
  6958. }
  6959. class xpath_node_set_raw
  6960. {
  6961. xpath_node_set::type_t _type;
  6962. xpath_node* _begin;
  6963. xpath_node* _end;
  6964. xpath_node* _eos;
  6965. public:
  6966. xpath_node_set_raw(): _type(xpath_node_set::type_unsorted), _begin(0), _end(0), _eos(0)
  6967. {
  6968. }
  6969. xpath_node* begin() const
  6970. {
  6971. return _begin;
  6972. }
  6973. xpath_node* end() const
  6974. {
  6975. return _end;
  6976. }
  6977. bool empty() const
  6978. {
  6979. return _begin == _end;
  6980. }
  6981. size_t size() const
  6982. {
  6983. return static_cast<size_t>(_end - _begin);
  6984. }
  6985. xpath_node first() const
  6986. {
  6987. return xpath_first(_begin, _end, _type);
  6988. }
  6989. void push_back_grow(const xpath_node& node, xpath_allocator* alloc);
  6990. void push_back(const xpath_node& node, xpath_allocator* alloc)
  6991. {
  6992. if (_end != _eos)
  6993. *_end++ = node;
  6994. else
  6995. push_back_grow(node, alloc);
  6996. }
  6997. void append(const xpath_node* begin_, const xpath_node* end_, xpath_allocator* alloc)
  6998. {
  6999. if (begin_ == end_) return;
  7000. size_t size_ = static_cast<size_t>(_end - _begin);
  7001. size_t capacity = static_cast<size_t>(_eos - _begin);
  7002. size_t count = static_cast<size_t>(end_ - begin_);
  7003. if (size_ + count > capacity)
  7004. {
  7005. // reallocate the old array or allocate a new one
  7006. xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), (size_ + count) * sizeof(xpath_node)));
  7007. if (!data) return;
  7008. // finalize
  7009. _begin = data;
  7010. _end = data + size_;
  7011. _eos = data + size_ + count;
  7012. }
  7013. memcpy(_end, begin_, count * sizeof(xpath_node));
  7014. _end += count;
  7015. }
  7016. void sort_do()
  7017. {
  7018. _type = xpath_sort(_begin, _end, _type, false);
  7019. }
  7020. void truncate(xpath_node* pos)
  7021. {
  7022. assert(_begin <= pos && pos <= _end);
  7023. _end = pos;
  7024. }
  7025. void remove_duplicates(xpath_allocator* alloc)
  7026. {
  7027. if (_type == xpath_node_set::type_unsorted && _end - _begin > 2)
  7028. {
  7029. xpath_allocator_capture cr(alloc);
  7030. size_t size_ = static_cast<size_t>(_end - _begin);
  7031. size_t hash_size = 1;
  7032. while (hash_size < size_ + size_ / 2) hash_size *= 2;
  7033. const void** hash_data = static_cast<const void**>(alloc->allocate(hash_size * sizeof(void**)));
  7034. if (!hash_data) return;
  7035. memset(hash_data, 0, hash_size * sizeof(const void**));
  7036. xpath_node* write = _begin;
  7037. for (xpath_node* it = _begin; it != _end; ++it)
  7038. {
  7039. const void* attr = it->attribute().internal_object();
  7040. const void* node = it->node().internal_object();
  7041. const void* key = attr ? attr : node;
  7042. if (key && hash_insert(hash_data, hash_size, key))
  7043. {
  7044. *write++ = *it;
  7045. }
  7046. }
  7047. _end = write;
  7048. }
  7049. else
  7050. {
  7051. _end = unique(_begin, _end);
  7052. }
  7053. }
  7054. xpath_node_set::type_t type() const
  7055. {
  7056. return _type;
  7057. }
  7058. void set_type(xpath_node_set::type_t value)
  7059. {
  7060. _type = value;
  7061. }
  7062. };
  7063. PUGI__FN_NO_INLINE void xpath_node_set_raw::push_back_grow(const xpath_node& node, xpath_allocator* alloc)
  7064. {
  7065. size_t capacity = static_cast<size_t>(_eos - _begin);
  7066. // get new capacity (1.5x rule)
  7067. size_t new_capacity = capacity + capacity / 2 + 1;
  7068. // reallocate the old array or allocate a new one
  7069. xpath_node* data = static_cast<xpath_node*>(alloc->reallocate(_begin, capacity * sizeof(xpath_node), new_capacity * sizeof(xpath_node)));
  7070. if (!data) return;
  7071. // finalize
  7072. _begin = data;
  7073. _end = data + capacity;
  7074. _eos = data + new_capacity;
  7075. // push
  7076. *_end++ = node;
  7077. }
  7078. PUGI__NS_END
  7079. PUGI__NS_BEGIN
  7080. struct xpath_context
  7081. {
  7082. xpath_node n;
  7083. size_t position, size;
  7084. xpath_context(const xpath_node& n_, size_t position_, size_t size_): n(n_), position(position_), size(size_)
  7085. {
  7086. }
  7087. };
  7088. enum lexeme_t
  7089. {
  7090. lex_none = 0,
  7091. lex_equal,
  7092. lex_not_equal,
  7093. lex_less,
  7094. lex_greater,
  7095. lex_less_or_equal,
  7096. lex_greater_or_equal,
  7097. lex_plus,
  7098. lex_minus,
  7099. lex_multiply,
  7100. lex_union,
  7101. lex_var_ref,
  7102. lex_open_brace,
  7103. lex_close_brace,
  7104. lex_quoted_string,
  7105. lex_number,
  7106. lex_slash,
  7107. lex_double_slash,
  7108. lex_open_square_brace,
  7109. lex_close_square_brace,
  7110. lex_string,
  7111. lex_comma,
  7112. lex_axis_attribute,
  7113. lex_dot,
  7114. lex_double_dot,
  7115. lex_double_colon,
  7116. lex_eof
  7117. };
  7118. struct xpath_lexer_string
  7119. {
  7120. const char_t* begin;
  7121. const char_t* end;
  7122. xpath_lexer_string(): begin(0), end(0)
  7123. {
  7124. }
  7125. bool operator==(const char_t* other) const
  7126. {
  7127. size_t length = static_cast<size_t>(end - begin);
  7128. return strequalrange(other, begin, length);
  7129. }
  7130. };
  7131. class xpath_lexer
  7132. {
  7133. const char_t* _cur;
  7134. const char_t* _cur_lexeme_pos;
  7135. xpath_lexer_string _cur_lexeme_contents;
  7136. lexeme_t _cur_lexeme;
  7137. public:
  7138. explicit xpath_lexer(const char_t* query): _cur(query)
  7139. {
  7140. next();
  7141. }
  7142. const char_t* state() const
  7143. {
  7144. return _cur;
  7145. }
  7146. void next()
  7147. {
  7148. const char_t* cur = _cur;
  7149. while (PUGI__IS_CHARTYPE(*cur, ct_space)) ++cur;
  7150. // save lexeme position for error reporting
  7151. _cur_lexeme_pos = cur;
  7152. switch (*cur)
  7153. {
  7154. case 0:
  7155. _cur_lexeme = lex_eof;
  7156. break;
  7157. case '>':
  7158. if (*(cur+1) == '=')
  7159. {
  7160. cur += 2;
  7161. _cur_lexeme = lex_greater_or_equal;
  7162. }
  7163. else
  7164. {
  7165. cur += 1;
  7166. _cur_lexeme = lex_greater;
  7167. }
  7168. break;
  7169. case '<':
  7170. if (*(cur+1) == '=')
  7171. {
  7172. cur += 2;
  7173. _cur_lexeme = lex_less_or_equal;
  7174. }
  7175. else
  7176. {
  7177. cur += 1;
  7178. _cur_lexeme = lex_less;
  7179. }
  7180. break;
  7181. case '!':
  7182. if (*(cur+1) == '=')
  7183. {
  7184. cur += 2;
  7185. _cur_lexeme = lex_not_equal;
  7186. }
  7187. else
  7188. {
  7189. _cur_lexeme = lex_none;
  7190. }
  7191. break;
  7192. case '=':
  7193. cur += 1;
  7194. _cur_lexeme = lex_equal;
  7195. break;
  7196. case '+':
  7197. cur += 1;
  7198. _cur_lexeme = lex_plus;
  7199. break;
  7200. case '-':
  7201. cur += 1;
  7202. _cur_lexeme = lex_minus;
  7203. break;
  7204. case '*':
  7205. cur += 1;
  7206. _cur_lexeme = lex_multiply;
  7207. break;
  7208. case '|':
  7209. cur += 1;
  7210. _cur_lexeme = lex_union;
  7211. break;
  7212. case '$':
  7213. cur += 1;
  7214. if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
  7215. {
  7216. _cur_lexeme_contents.begin = cur;
  7217. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  7218. if (cur[0] == ':' && PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // qname
  7219. {
  7220. cur++; // :
  7221. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  7222. }
  7223. _cur_lexeme_contents.end = cur;
  7224. _cur_lexeme = lex_var_ref;
  7225. }
  7226. else
  7227. {
  7228. _cur_lexeme = lex_none;
  7229. }
  7230. break;
  7231. case '(':
  7232. cur += 1;
  7233. _cur_lexeme = lex_open_brace;
  7234. break;
  7235. case ')':
  7236. cur += 1;
  7237. _cur_lexeme = lex_close_brace;
  7238. break;
  7239. case '[':
  7240. cur += 1;
  7241. _cur_lexeme = lex_open_square_brace;
  7242. break;
  7243. case ']':
  7244. cur += 1;
  7245. _cur_lexeme = lex_close_square_brace;
  7246. break;
  7247. case ',':
  7248. cur += 1;
  7249. _cur_lexeme = lex_comma;
  7250. break;
  7251. case '/':
  7252. if (*(cur+1) == '/')
  7253. {
  7254. cur += 2;
  7255. _cur_lexeme = lex_double_slash;
  7256. }
  7257. else
  7258. {
  7259. cur += 1;
  7260. _cur_lexeme = lex_slash;
  7261. }
  7262. break;
  7263. case '.':
  7264. if (*(cur+1) == '.')
  7265. {
  7266. cur += 2;
  7267. _cur_lexeme = lex_double_dot;
  7268. }
  7269. else if (PUGI__IS_CHARTYPEX(*(cur+1), ctx_digit))
  7270. {
  7271. _cur_lexeme_contents.begin = cur; // .
  7272. ++cur;
  7273. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  7274. _cur_lexeme_contents.end = cur;
  7275. _cur_lexeme = lex_number;
  7276. }
  7277. else
  7278. {
  7279. cur += 1;
  7280. _cur_lexeme = lex_dot;
  7281. }
  7282. break;
  7283. case '@':
  7284. cur += 1;
  7285. _cur_lexeme = lex_axis_attribute;
  7286. break;
  7287. case '"':
  7288. case '\'':
  7289. {
  7290. char_t terminator = *cur;
  7291. ++cur;
  7292. _cur_lexeme_contents.begin = cur;
  7293. while (*cur && *cur != terminator) cur++;
  7294. _cur_lexeme_contents.end = cur;
  7295. if (!*cur)
  7296. _cur_lexeme = lex_none;
  7297. else
  7298. {
  7299. cur += 1;
  7300. _cur_lexeme = lex_quoted_string;
  7301. }
  7302. break;
  7303. }
  7304. case ':':
  7305. if (*(cur+1) == ':')
  7306. {
  7307. cur += 2;
  7308. _cur_lexeme = lex_double_colon;
  7309. }
  7310. else
  7311. {
  7312. _cur_lexeme = lex_none;
  7313. }
  7314. break;
  7315. default:
  7316. if (PUGI__IS_CHARTYPEX(*cur, ctx_digit))
  7317. {
  7318. _cur_lexeme_contents.begin = cur;
  7319. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  7320. if (*cur == '.')
  7321. {
  7322. cur++;
  7323. while (PUGI__IS_CHARTYPEX(*cur, ctx_digit)) cur++;
  7324. }
  7325. _cur_lexeme_contents.end = cur;
  7326. _cur_lexeme = lex_number;
  7327. }
  7328. else if (PUGI__IS_CHARTYPEX(*cur, ctx_start_symbol))
  7329. {
  7330. _cur_lexeme_contents.begin = cur;
  7331. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  7332. if (cur[0] == ':')
  7333. {
  7334. if (cur[1] == '*') // namespace test ncname:*
  7335. {
  7336. cur += 2; // :*
  7337. }
  7338. else if (PUGI__IS_CHARTYPEX(cur[1], ctx_symbol)) // namespace test qname
  7339. {
  7340. cur++; // :
  7341. while (PUGI__IS_CHARTYPEX(*cur, ctx_symbol)) cur++;
  7342. }
  7343. }
  7344. _cur_lexeme_contents.end = cur;
  7345. _cur_lexeme = lex_string;
  7346. }
  7347. else
  7348. {
  7349. _cur_lexeme = lex_none;
  7350. }
  7351. }
  7352. _cur = cur;
  7353. }
  7354. lexeme_t current() const
  7355. {
  7356. return _cur_lexeme;
  7357. }
  7358. const char_t* current_pos() const
  7359. {
  7360. return _cur_lexeme_pos;
  7361. }
  7362. const xpath_lexer_string& contents() const
  7363. {
  7364. assert(_cur_lexeme == lex_var_ref || _cur_lexeme == lex_number || _cur_lexeme == lex_string || _cur_lexeme == lex_quoted_string);
  7365. return _cur_lexeme_contents;
  7366. }
  7367. };
  7368. enum ast_type_t
  7369. {
  7370. ast_unknown,
  7371. ast_op_or, // left or right
  7372. ast_op_and, // left and right
  7373. ast_op_equal, // left = right
  7374. ast_op_not_equal, // left != right
  7375. ast_op_less, // left < right
  7376. ast_op_greater, // left > right
  7377. ast_op_less_or_equal, // left <= right
  7378. ast_op_greater_or_equal, // left >= right
  7379. ast_op_add, // left + right
  7380. ast_op_subtract, // left - right
  7381. ast_op_multiply, // left * right
  7382. ast_op_divide, // left / right
  7383. ast_op_mod, // left % right
  7384. ast_op_negate, // left - right
  7385. ast_op_union, // left | right
  7386. ast_predicate, // apply predicate to set; next points to next predicate
  7387. ast_filter, // select * from left where right
  7388. ast_string_constant, // string constant
  7389. ast_number_constant, // number constant
  7390. ast_variable, // variable
  7391. ast_func_last, // last()
  7392. ast_func_position, // position()
  7393. ast_func_count, // count(left)
  7394. ast_func_id, // id(left)
  7395. ast_func_local_name_0, // local-name()
  7396. ast_func_local_name_1, // local-name(left)
  7397. ast_func_namespace_uri_0, // namespace-uri()
  7398. ast_func_namespace_uri_1, // namespace-uri(left)
  7399. ast_func_name_0, // name()
  7400. ast_func_name_1, // name(left)
  7401. ast_func_string_0, // string()
  7402. ast_func_string_1, // string(left)
  7403. ast_func_concat, // concat(left, right, siblings)
  7404. ast_func_starts_with, // starts_with(left, right)
  7405. ast_func_contains, // contains(left, right)
  7406. ast_func_substring_before, // substring-before(left, right)
  7407. ast_func_substring_after, // substring-after(left, right)
  7408. ast_func_substring_2, // substring(left, right)
  7409. ast_func_substring_3, // substring(left, right, third)
  7410. ast_func_string_length_0, // string-length()
  7411. ast_func_string_length_1, // string-length(left)
  7412. ast_func_normalize_space_0, // normalize-space()
  7413. ast_func_normalize_space_1, // normalize-space(left)
  7414. ast_func_translate, // translate(left, right, third)
  7415. ast_func_boolean, // boolean(left)
  7416. ast_func_not, // not(left)
  7417. ast_func_true, // true()
  7418. ast_func_false, // false()
  7419. ast_func_lang, // lang(left)
  7420. ast_func_number_0, // number()
  7421. ast_func_number_1, // number(left)
  7422. ast_func_sum, // sum(left)
  7423. ast_func_floor, // floor(left)
  7424. ast_func_ceiling, // ceiling(left)
  7425. ast_func_round, // round(left)
  7426. ast_step, // process set left with step
  7427. ast_step_root, // select root node
  7428. ast_opt_translate_table, // translate(left, right, third) where right/third are constants
  7429. ast_opt_compare_attribute // @name = 'string'
  7430. };
  7431. enum axis_t
  7432. {
  7433. axis_ancestor,
  7434. axis_ancestor_or_self,
  7435. axis_attribute,
  7436. axis_child,
  7437. axis_descendant,
  7438. axis_descendant_or_self,
  7439. axis_following,
  7440. axis_following_sibling,
  7441. axis_namespace,
  7442. axis_parent,
  7443. axis_preceding,
  7444. axis_preceding_sibling,
  7445. axis_self
  7446. };
  7447. enum nodetest_t
  7448. {
  7449. nodetest_none,
  7450. nodetest_name,
  7451. nodetest_type_node,
  7452. nodetest_type_comment,
  7453. nodetest_type_pi,
  7454. nodetest_type_text,
  7455. nodetest_pi,
  7456. nodetest_all,
  7457. nodetest_all_in_namespace
  7458. };
  7459. enum predicate_t
  7460. {
  7461. predicate_default,
  7462. predicate_posinv,
  7463. predicate_constant,
  7464. predicate_constant_one
  7465. };
  7466. enum nodeset_eval_t
  7467. {
  7468. nodeset_eval_all,
  7469. nodeset_eval_any,
  7470. nodeset_eval_first
  7471. };
  7472. template <axis_t N> struct axis_to_type
  7473. {
  7474. static const axis_t axis;
  7475. };
  7476. template <axis_t N> const axis_t axis_to_type<N>::axis = N;
  7477. class xpath_ast_node
  7478. {
  7479. private:
  7480. // node type
  7481. char _type;
  7482. char _rettype;
  7483. // for ast_step
  7484. char _axis;
  7485. // for ast_step/ast_predicate/ast_filter
  7486. char _test;
  7487. // tree node structure
  7488. xpath_ast_node* _left;
  7489. xpath_ast_node* _right;
  7490. xpath_ast_node* _next;
  7491. union
  7492. {
  7493. // value for ast_string_constant
  7494. const char_t* string;
  7495. // value for ast_number_constant
  7496. double number;
  7497. // variable for ast_variable
  7498. xpath_variable* variable;
  7499. // node test for ast_step (node name/namespace/node type/pi target)
  7500. const char_t* nodetest;
  7501. // table for ast_opt_translate_table
  7502. const unsigned char* table;
  7503. } _data;
  7504. xpath_ast_node(const xpath_ast_node&);
  7505. xpath_ast_node& operator=(const xpath_ast_node&);
  7506. 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)
  7507. {
  7508. xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
  7509. if (lt != xpath_type_node_set && rt != xpath_type_node_set)
  7510. {
  7511. if (lt == xpath_type_boolean || rt == xpath_type_boolean)
  7512. return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
  7513. else if (lt == xpath_type_number || rt == xpath_type_number)
  7514. return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
  7515. else if (lt == xpath_type_string || rt == xpath_type_string)
  7516. {
  7517. xpath_allocator_capture cr(stack.result);
  7518. xpath_string ls = lhs->eval_string(c, stack);
  7519. xpath_string rs = rhs->eval_string(c, stack);
  7520. return comp(ls, rs);
  7521. }
  7522. }
  7523. else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
  7524. {
  7525. xpath_allocator_capture cr(stack.result);
  7526. xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
  7527. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  7528. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  7529. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  7530. {
  7531. xpath_allocator_capture cri(stack.result);
  7532. if (comp(string_value(*li, stack.result), string_value(*ri, stack.result)))
  7533. return true;
  7534. }
  7535. return false;
  7536. }
  7537. else
  7538. {
  7539. if (lt == xpath_type_node_set)
  7540. {
  7541. swap(lhs, rhs);
  7542. swap(lt, rt);
  7543. }
  7544. if (lt == xpath_type_boolean)
  7545. return comp(lhs->eval_boolean(c, stack), rhs->eval_boolean(c, stack));
  7546. else if (lt == xpath_type_number)
  7547. {
  7548. xpath_allocator_capture cr(stack.result);
  7549. double l = lhs->eval_number(c, stack);
  7550. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  7551. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  7552. {
  7553. xpath_allocator_capture cri(stack.result);
  7554. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  7555. return true;
  7556. }
  7557. return false;
  7558. }
  7559. else if (lt == xpath_type_string)
  7560. {
  7561. xpath_allocator_capture cr(stack.result);
  7562. xpath_string l = lhs->eval_string(c, stack);
  7563. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  7564. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  7565. {
  7566. xpath_allocator_capture cri(stack.result);
  7567. if (comp(l, string_value(*ri, stack.result)))
  7568. return true;
  7569. }
  7570. return false;
  7571. }
  7572. }
  7573. assert(false && "Wrong types"); // unreachable
  7574. return false;
  7575. }
  7576. static bool eval_once(xpath_node_set::type_t type, nodeset_eval_t eval)
  7577. {
  7578. return type == xpath_node_set::type_sorted ? eval != nodeset_eval_all : eval == nodeset_eval_any;
  7579. }
  7580. 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)
  7581. {
  7582. xpath_value_type lt = lhs->rettype(), rt = rhs->rettype();
  7583. if (lt != xpath_type_node_set && rt != xpath_type_node_set)
  7584. return comp(lhs->eval_number(c, stack), rhs->eval_number(c, stack));
  7585. else if (lt == xpath_type_node_set && rt == xpath_type_node_set)
  7586. {
  7587. xpath_allocator_capture cr(stack.result);
  7588. xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
  7589. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  7590. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  7591. {
  7592. xpath_allocator_capture cri(stack.result);
  7593. double l = convert_string_to_number(string_value(*li, stack.result).c_str());
  7594. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  7595. {
  7596. xpath_allocator_capture crii(stack.result);
  7597. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  7598. return true;
  7599. }
  7600. }
  7601. return false;
  7602. }
  7603. else if (lt != xpath_type_node_set && rt == xpath_type_node_set)
  7604. {
  7605. xpath_allocator_capture cr(stack.result);
  7606. double l = lhs->eval_number(c, stack);
  7607. xpath_node_set_raw rs = rhs->eval_node_set(c, stack, nodeset_eval_all);
  7608. for (const xpath_node* ri = rs.begin(); ri != rs.end(); ++ri)
  7609. {
  7610. xpath_allocator_capture cri(stack.result);
  7611. if (comp(l, convert_string_to_number(string_value(*ri, stack.result).c_str())))
  7612. return true;
  7613. }
  7614. return false;
  7615. }
  7616. else if (lt == xpath_type_node_set && rt != xpath_type_node_set)
  7617. {
  7618. xpath_allocator_capture cr(stack.result);
  7619. xpath_node_set_raw ls = lhs->eval_node_set(c, stack, nodeset_eval_all);
  7620. double r = rhs->eval_number(c, stack);
  7621. for (const xpath_node* li = ls.begin(); li != ls.end(); ++li)
  7622. {
  7623. xpath_allocator_capture cri(stack.result);
  7624. if (comp(convert_string_to_number(string_value(*li, stack.result).c_str()), r))
  7625. return true;
  7626. }
  7627. return false;
  7628. }
  7629. else
  7630. {
  7631. assert(false && "Wrong types"); // unreachable
  7632. return false;
  7633. }
  7634. }
  7635. static void apply_predicate_boolean(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once)
  7636. {
  7637. assert(ns.size() >= first);
  7638. assert(expr->rettype() != xpath_type_number);
  7639. size_t i = 1;
  7640. size_t size = ns.size() - first;
  7641. xpath_node* last = ns.begin() + first;
  7642. // remove_if... or well, sort of
  7643. for (xpath_node* it = last; it != ns.end(); ++it, ++i)
  7644. {
  7645. xpath_context c(*it, i, size);
  7646. if (expr->eval_boolean(c, stack))
  7647. {
  7648. *last++ = *it;
  7649. if (once) break;
  7650. }
  7651. }
  7652. ns.truncate(last);
  7653. }
  7654. static void apply_predicate_number(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack, bool once)
  7655. {
  7656. assert(ns.size() >= first);
  7657. assert(expr->rettype() == xpath_type_number);
  7658. size_t i = 1;
  7659. size_t size = ns.size() - first;
  7660. xpath_node* last = ns.begin() + first;
  7661. // remove_if... or well, sort of
  7662. for (xpath_node* it = last; it != ns.end(); ++it, ++i)
  7663. {
  7664. xpath_context c(*it, i, size);
  7665. if (expr->eval_number(c, stack) == i)
  7666. {
  7667. *last++ = *it;
  7668. if (once) break;
  7669. }
  7670. }
  7671. ns.truncate(last);
  7672. }
  7673. static void apply_predicate_number_const(xpath_node_set_raw& ns, size_t first, xpath_ast_node* expr, const xpath_stack& stack)
  7674. {
  7675. assert(ns.size() >= first);
  7676. assert(expr->rettype() == xpath_type_number);
  7677. size_t size = ns.size() - first;
  7678. xpath_node* last = ns.begin() + first;
  7679. xpath_context c(xpath_node(), 1, size);
  7680. double er = expr->eval_number(c, stack);
  7681. if (er >= 1.0 && er <= size)
  7682. {
  7683. size_t eri = static_cast<size_t>(er);
  7684. if (er == eri)
  7685. {
  7686. xpath_node r = last[eri - 1];
  7687. *last++ = r;
  7688. }
  7689. }
  7690. ns.truncate(last);
  7691. }
  7692. void apply_predicate(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, bool once)
  7693. {
  7694. if (ns.size() == first) return;
  7695. assert(_type == ast_filter || _type == ast_predicate);
  7696. if (_test == predicate_constant || _test == predicate_constant_one)
  7697. apply_predicate_number_const(ns, first, _right, stack);
  7698. else if (_right->rettype() == xpath_type_number)
  7699. apply_predicate_number(ns, first, _right, stack, once);
  7700. else
  7701. apply_predicate_boolean(ns, first, _right, stack, once);
  7702. }
  7703. void apply_predicates(xpath_node_set_raw& ns, size_t first, const xpath_stack& stack, nodeset_eval_t eval)
  7704. {
  7705. if (ns.size() == first) return;
  7706. bool last_once = eval_once(ns.type(), eval);
  7707. for (xpath_ast_node* pred = _right; pred; pred = pred->_next)
  7708. pred->apply_predicate(ns, first, stack, !pred->_next && last_once);
  7709. }
  7710. bool step_push(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* parent, xpath_allocator* alloc)
  7711. {
  7712. assert(a);
  7713. const char_t* name = a->name ? a->name + 0 : PUGIXML_TEXT("");
  7714. switch (_test)
  7715. {
  7716. case nodetest_name:
  7717. if (strequal(name, _data.nodetest) && is_xpath_attribute(name))
  7718. {
  7719. ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
  7720. return true;
  7721. }
  7722. break;
  7723. case nodetest_type_node:
  7724. case nodetest_all:
  7725. if (is_xpath_attribute(name))
  7726. {
  7727. ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
  7728. return true;
  7729. }
  7730. break;
  7731. case nodetest_all_in_namespace:
  7732. if (starts_with(name, _data.nodetest) && is_xpath_attribute(name))
  7733. {
  7734. ns.push_back(xpath_node(xml_attribute(a), xml_node(parent)), alloc);
  7735. return true;
  7736. }
  7737. break;
  7738. default:
  7739. ;
  7740. }
  7741. return false;
  7742. }
  7743. bool step_push(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc)
  7744. {
  7745. assert(n);
  7746. xml_node_type type = PUGI__NODETYPE(n);
  7747. switch (_test)
  7748. {
  7749. case nodetest_name:
  7750. if (type == node_element && n->name && strequal(n->name, _data.nodetest))
  7751. {
  7752. ns.push_back(xml_node(n), alloc);
  7753. return true;
  7754. }
  7755. break;
  7756. case nodetest_type_node:
  7757. ns.push_back(xml_node(n), alloc);
  7758. return true;
  7759. case nodetest_type_comment:
  7760. if (type == node_comment)
  7761. {
  7762. ns.push_back(xml_node(n), alloc);
  7763. return true;
  7764. }
  7765. break;
  7766. case nodetest_type_text:
  7767. if (type == node_pcdata || type == node_cdata)
  7768. {
  7769. ns.push_back(xml_node(n), alloc);
  7770. return true;
  7771. }
  7772. break;
  7773. case nodetest_type_pi:
  7774. if (type == node_pi)
  7775. {
  7776. ns.push_back(xml_node(n), alloc);
  7777. return true;
  7778. }
  7779. break;
  7780. case nodetest_pi:
  7781. if (type == node_pi && n->name && strequal(n->name, _data.nodetest))
  7782. {
  7783. ns.push_back(xml_node(n), alloc);
  7784. return true;
  7785. }
  7786. break;
  7787. case nodetest_all:
  7788. if (type == node_element)
  7789. {
  7790. ns.push_back(xml_node(n), alloc);
  7791. return true;
  7792. }
  7793. break;
  7794. case nodetest_all_in_namespace:
  7795. if (type == node_element && n->name && starts_with(n->name, _data.nodetest))
  7796. {
  7797. ns.push_back(xml_node(n), alloc);
  7798. return true;
  7799. }
  7800. break;
  7801. default:
  7802. assert(false && "Unknown axis"); // unreachable
  7803. }
  7804. return false;
  7805. }
  7806. template <class T> void step_fill(xpath_node_set_raw& ns, xml_node_struct* n, xpath_allocator* alloc, bool once, T)
  7807. {
  7808. const axis_t axis = T::axis;
  7809. switch (axis)
  7810. {
  7811. case axis_attribute:
  7812. {
  7813. for (xml_attribute_struct* a = n->first_attribute; a; a = a->next_attribute)
  7814. if (step_push(ns, a, n, alloc) & once)
  7815. return;
  7816. break;
  7817. }
  7818. case axis_child:
  7819. {
  7820. for (xml_node_struct* c = n->first_child; c; c = c->next_sibling)
  7821. if (step_push(ns, c, alloc) & once)
  7822. return;
  7823. break;
  7824. }
  7825. case axis_descendant:
  7826. case axis_descendant_or_self:
  7827. {
  7828. if (axis == axis_descendant_or_self)
  7829. if (step_push(ns, n, alloc) & once)
  7830. return;
  7831. xml_node_struct* cur = n->first_child;
  7832. while (cur)
  7833. {
  7834. if (step_push(ns, cur, alloc) & once)
  7835. return;
  7836. if (cur->first_child)
  7837. cur = cur->first_child;
  7838. else
  7839. {
  7840. while (!cur->next_sibling)
  7841. {
  7842. cur = cur->parent;
  7843. if (cur == n) return;
  7844. }
  7845. cur = cur->next_sibling;
  7846. }
  7847. }
  7848. break;
  7849. }
  7850. case axis_following_sibling:
  7851. {
  7852. for (xml_node_struct* c = n->next_sibling; c; c = c->next_sibling)
  7853. if (step_push(ns, c, alloc) & once)
  7854. return;
  7855. break;
  7856. }
  7857. case axis_preceding_sibling:
  7858. {
  7859. for (xml_node_struct* c = n->prev_sibling_c; c->next_sibling; c = c->prev_sibling_c)
  7860. if (step_push(ns, c, alloc) & once)
  7861. return;
  7862. break;
  7863. }
  7864. case axis_following:
  7865. {
  7866. xml_node_struct* cur = n;
  7867. // exit from this node so that we don't include descendants
  7868. while (!cur->next_sibling)
  7869. {
  7870. cur = cur->parent;
  7871. if (!cur) return;
  7872. }
  7873. cur = cur->next_sibling;
  7874. while (cur)
  7875. {
  7876. if (step_push(ns, cur, alloc) & once)
  7877. return;
  7878. if (cur->first_child)
  7879. cur = cur->first_child;
  7880. else
  7881. {
  7882. while (!cur->next_sibling)
  7883. {
  7884. cur = cur->parent;
  7885. if (!cur) return;
  7886. }
  7887. cur = cur->next_sibling;
  7888. }
  7889. }
  7890. break;
  7891. }
  7892. case axis_preceding:
  7893. {
  7894. xml_node_struct* cur = n;
  7895. // exit from this node so that we don't include descendants
  7896. while (!cur->prev_sibling_c->next_sibling)
  7897. {
  7898. cur = cur->parent;
  7899. if (!cur) return;
  7900. }
  7901. cur = cur->prev_sibling_c;
  7902. while (cur)
  7903. {
  7904. if (cur->first_child)
  7905. cur = cur->first_child->prev_sibling_c;
  7906. else
  7907. {
  7908. // leaf node, can't be ancestor
  7909. if (step_push(ns, cur, alloc) & once)
  7910. return;
  7911. while (!cur->prev_sibling_c->next_sibling)
  7912. {
  7913. cur = cur->parent;
  7914. if (!cur) return;
  7915. if (!node_is_ancestor(cur, n))
  7916. if (step_push(ns, cur, alloc) & once)
  7917. return;
  7918. }
  7919. cur = cur->prev_sibling_c;
  7920. }
  7921. }
  7922. break;
  7923. }
  7924. case axis_ancestor:
  7925. case axis_ancestor_or_self:
  7926. {
  7927. if (axis == axis_ancestor_or_self)
  7928. if (step_push(ns, n, alloc) & once)
  7929. return;
  7930. xml_node_struct* cur = n->parent;
  7931. while (cur)
  7932. {
  7933. if (step_push(ns, cur, alloc) & once)
  7934. return;
  7935. cur = cur->parent;
  7936. }
  7937. break;
  7938. }
  7939. case axis_self:
  7940. {
  7941. step_push(ns, n, alloc);
  7942. break;
  7943. }
  7944. case axis_parent:
  7945. {
  7946. if (n->parent)
  7947. step_push(ns, n->parent, alloc);
  7948. break;
  7949. }
  7950. default:
  7951. assert(false && "Unimplemented axis"); // unreachable
  7952. }
  7953. }
  7954. template <class T> void step_fill(xpath_node_set_raw& ns, xml_attribute_struct* a, xml_node_struct* p, xpath_allocator* alloc, bool once, T v)
  7955. {
  7956. const axis_t axis = T::axis;
  7957. switch (axis)
  7958. {
  7959. case axis_ancestor:
  7960. case axis_ancestor_or_self:
  7961. {
  7962. if (axis == axis_ancestor_or_self && _test == nodetest_type_node) // reject attributes based on principal node type test
  7963. if (step_push(ns, a, p, alloc) & once)
  7964. return;
  7965. xml_node_struct* cur = p;
  7966. while (cur)
  7967. {
  7968. if (step_push(ns, cur, alloc) & once)
  7969. return;
  7970. cur = cur->parent;
  7971. }
  7972. break;
  7973. }
  7974. case axis_descendant_or_self:
  7975. case axis_self:
  7976. {
  7977. if (_test == nodetest_type_node) // reject attributes based on principal node type test
  7978. step_push(ns, a, p, alloc);
  7979. break;
  7980. }
  7981. case axis_following:
  7982. {
  7983. xml_node_struct* cur = p;
  7984. while (cur)
  7985. {
  7986. if (cur->first_child)
  7987. cur = cur->first_child;
  7988. else
  7989. {
  7990. while (!cur->next_sibling)
  7991. {
  7992. cur = cur->parent;
  7993. if (!cur) return;
  7994. }
  7995. cur = cur->next_sibling;
  7996. }
  7997. if (step_push(ns, cur, alloc) & once)
  7998. return;
  7999. }
  8000. break;
  8001. }
  8002. case axis_parent:
  8003. {
  8004. step_push(ns, p, alloc);
  8005. break;
  8006. }
  8007. case axis_preceding:
  8008. {
  8009. // preceding:: axis does not include attribute nodes and attribute ancestors (they are the same as parent's ancestors), so we can reuse node preceding
  8010. step_fill(ns, p, alloc, once, v);
  8011. break;
  8012. }
  8013. default:
  8014. assert(false && "Unimplemented axis"); // unreachable
  8015. }
  8016. }
  8017. template <class T> void step_fill(xpath_node_set_raw& ns, const xpath_node& xn, xpath_allocator* alloc, bool once, T v)
  8018. {
  8019. const axis_t axis = T::axis;
  8020. const bool axis_has_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);
  8021. if (xn.node())
  8022. step_fill(ns, xn.node().internal_object(), alloc, once, v);
  8023. else if (axis_has_attributes && xn.attribute() && xn.parent())
  8024. step_fill(ns, xn.attribute().internal_object(), xn.parent().internal_object(), alloc, once, v);
  8025. }
  8026. template <class T> xpath_node_set_raw step_do(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval, T v)
  8027. {
  8028. const axis_t axis = T::axis;
  8029. const bool axis_reverse = (axis == axis_ancestor || axis == axis_ancestor_or_self || axis == axis_preceding || axis == axis_preceding_sibling);
  8030. const xpath_node_set::type_t axis_type = axis_reverse ? xpath_node_set::type_sorted_reverse : xpath_node_set::type_sorted;
  8031. bool once =
  8032. (axis == axis_attribute && _test == nodetest_name) ||
  8033. (!_right && eval_once(axis_type, eval)) ||
  8034. // coverity[mixed_enums]
  8035. (_right && !_right->_next && _right->_test == predicate_constant_one);
  8036. xpath_node_set_raw ns;
  8037. ns.set_type(axis_type);
  8038. if (_left)
  8039. {
  8040. xpath_node_set_raw s = _left->eval_node_set(c, stack, nodeset_eval_all);
  8041. // self axis preserves the original order
  8042. if (axis == axis_self) ns.set_type(s.type());
  8043. for (const xpath_node* it = s.begin(); it != s.end(); ++it)
  8044. {
  8045. size_t size = ns.size();
  8046. // in general, all axes generate elements in a particular order, but there is no order guarantee if axis is applied to two nodes
  8047. if (axis != axis_self && size != 0) ns.set_type(xpath_node_set::type_unsorted);
  8048. step_fill(ns, *it, stack.result, once, v);
  8049. if (_right) apply_predicates(ns, size, stack, eval);
  8050. }
  8051. }
  8052. else
  8053. {
  8054. step_fill(ns, c.n, stack.result, once, v);
  8055. if (_right) apply_predicates(ns, 0, stack, eval);
  8056. }
  8057. // child, attribute and self axes always generate unique set of nodes
  8058. // for other axis, if the set stayed sorted, it stayed unique because the traversal algorithms do not visit the same node twice
  8059. if (axis != axis_child && axis != axis_attribute && axis != axis_self && ns.type() == xpath_node_set::type_unsorted)
  8060. ns.remove_duplicates(stack.temp);
  8061. return ns;
  8062. }
  8063. public:
  8064. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, const char_t* value):
  8065. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  8066. {
  8067. assert(type == ast_string_constant);
  8068. _data.string = value;
  8069. }
  8070. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, double value):
  8071. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  8072. {
  8073. assert(type == ast_number_constant);
  8074. _data.number = value;
  8075. }
  8076. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_variable* value):
  8077. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(0), _right(0), _next(0)
  8078. {
  8079. assert(type == ast_variable);
  8080. _data.variable = value;
  8081. }
  8082. xpath_ast_node(ast_type_t type, xpath_value_type rettype_, xpath_ast_node* left = 0, xpath_ast_node* right = 0):
  8083. _type(static_cast<char>(type)), _rettype(static_cast<char>(rettype_)), _axis(0), _test(0), _left(left), _right(right), _next(0)
  8084. {
  8085. }
  8086. xpath_ast_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents):
  8087. _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)
  8088. {
  8089. assert(type == ast_step);
  8090. _data.nodetest = contents;
  8091. }
  8092. xpath_ast_node(ast_type_t type, xpath_ast_node* left, xpath_ast_node* right, predicate_t test):
  8093. _type(static_cast<char>(type)), _rettype(xpath_type_node_set), _axis(0), _test(static_cast<char>(test)), _left(left), _right(right), _next(0)
  8094. {
  8095. assert(type == ast_filter || type == ast_predicate);
  8096. }
  8097. void set_next(xpath_ast_node* value)
  8098. {
  8099. _next = value;
  8100. }
  8101. void set_right(xpath_ast_node* value)
  8102. {
  8103. _right = value;
  8104. }
  8105. bool eval_boolean(const xpath_context& c, const xpath_stack& stack)
  8106. {
  8107. switch (_type)
  8108. {
  8109. case ast_op_or:
  8110. return _left->eval_boolean(c, stack) || _right->eval_boolean(c, stack);
  8111. case ast_op_and:
  8112. return _left->eval_boolean(c, stack) && _right->eval_boolean(c, stack);
  8113. case ast_op_equal:
  8114. return compare_eq(_left, _right, c, stack, equal_to());
  8115. case ast_op_not_equal:
  8116. return compare_eq(_left, _right, c, stack, not_equal_to());
  8117. case ast_op_less:
  8118. return compare_rel(_left, _right, c, stack, less());
  8119. case ast_op_greater:
  8120. return compare_rel(_right, _left, c, stack, less());
  8121. case ast_op_less_or_equal:
  8122. return compare_rel(_left, _right, c, stack, less_equal());
  8123. case ast_op_greater_or_equal:
  8124. return compare_rel(_right, _left, c, stack, less_equal());
  8125. case ast_func_starts_with:
  8126. {
  8127. xpath_allocator_capture cr(stack.result);
  8128. xpath_string lr = _left->eval_string(c, stack);
  8129. xpath_string rr = _right->eval_string(c, stack);
  8130. return starts_with(lr.c_str(), rr.c_str());
  8131. }
  8132. case ast_func_contains:
  8133. {
  8134. xpath_allocator_capture cr(stack.result);
  8135. xpath_string lr = _left->eval_string(c, stack);
  8136. xpath_string rr = _right->eval_string(c, stack);
  8137. return find_substring(lr.c_str(), rr.c_str()) != 0;
  8138. }
  8139. case ast_func_boolean:
  8140. return _left->eval_boolean(c, stack);
  8141. case ast_func_not:
  8142. return !_left->eval_boolean(c, stack);
  8143. case ast_func_true:
  8144. return true;
  8145. case ast_func_false:
  8146. return false;
  8147. case ast_func_lang:
  8148. {
  8149. if (c.n.attribute()) return false;
  8150. xpath_allocator_capture cr(stack.result);
  8151. xpath_string lang = _left->eval_string(c, stack);
  8152. for (xml_node n = c.n.node(); n; n = n.parent())
  8153. {
  8154. xml_attribute a = n.attribute(PUGIXML_TEXT("xml:lang"));
  8155. if (a)
  8156. {
  8157. const char_t* value = a.value();
  8158. // strnicmp / strncasecmp is not portable
  8159. for (const char_t* lit = lang.c_str(); *lit; ++lit)
  8160. {
  8161. if (tolower_ascii(*lit) != tolower_ascii(*value)) return false;
  8162. ++value;
  8163. }
  8164. return *value == 0 || *value == '-';
  8165. }
  8166. }
  8167. return false;
  8168. }
  8169. case ast_opt_compare_attribute:
  8170. {
  8171. const char_t* value = (_right->_type == ast_string_constant) ? _right->_data.string : _right->_data.variable->get_string();
  8172. xml_attribute attr = c.n.node().attribute(_left->_data.nodetest);
  8173. return attr && strequal(attr.value(), value) && is_xpath_attribute(attr.name());
  8174. }
  8175. case ast_variable:
  8176. {
  8177. assert(_rettype == _data.variable->type());
  8178. if (_rettype == xpath_type_boolean)
  8179. return _data.variable->get_boolean();
  8180. }
  8181. // fallthrough
  8182. default:
  8183. {
  8184. switch (_rettype)
  8185. {
  8186. case xpath_type_number:
  8187. return convert_number_to_boolean(eval_number(c, stack));
  8188. case xpath_type_string:
  8189. {
  8190. xpath_allocator_capture cr(stack.result);
  8191. return !eval_string(c, stack).empty();
  8192. }
  8193. case xpath_type_node_set:
  8194. {
  8195. xpath_allocator_capture cr(stack.result);
  8196. return !eval_node_set(c, stack, nodeset_eval_any).empty();
  8197. }
  8198. default:
  8199. assert(false && "Wrong expression for return type boolean"); // unreachable
  8200. return false;
  8201. }
  8202. }
  8203. }
  8204. }
  8205. double eval_number(const xpath_context& c, const xpath_stack& stack)
  8206. {
  8207. switch (_type)
  8208. {
  8209. case ast_op_add:
  8210. return _left->eval_number(c, stack) + _right->eval_number(c, stack);
  8211. case ast_op_subtract:
  8212. return _left->eval_number(c, stack) - _right->eval_number(c, stack);
  8213. case ast_op_multiply:
  8214. return _left->eval_number(c, stack) * _right->eval_number(c, stack);
  8215. case ast_op_divide:
  8216. return _left->eval_number(c, stack) / _right->eval_number(c, stack);
  8217. case ast_op_mod:
  8218. return fmod(_left->eval_number(c, stack), _right->eval_number(c, stack));
  8219. case ast_op_negate:
  8220. return -_left->eval_number(c, stack);
  8221. case ast_number_constant:
  8222. return _data.number;
  8223. case ast_func_last:
  8224. return static_cast<double>(c.size);
  8225. case ast_func_position:
  8226. return static_cast<double>(c.position);
  8227. case ast_func_count:
  8228. {
  8229. xpath_allocator_capture cr(stack.result);
  8230. return static_cast<double>(_left->eval_node_set(c, stack, nodeset_eval_all).size());
  8231. }
  8232. case ast_func_string_length_0:
  8233. {
  8234. xpath_allocator_capture cr(stack.result);
  8235. return static_cast<double>(string_value(c.n, stack.result).length());
  8236. }
  8237. case ast_func_string_length_1:
  8238. {
  8239. xpath_allocator_capture cr(stack.result);
  8240. return static_cast<double>(_left->eval_string(c, stack).length());
  8241. }
  8242. case ast_func_number_0:
  8243. {
  8244. xpath_allocator_capture cr(stack.result);
  8245. return convert_string_to_number(string_value(c.n, stack.result).c_str());
  8246. }
  8247. case ast_func_number_1:
  8248. return _left->eval_number(c, stack);
  8249. case ast_func_sum:
  8250. {
  8251. xpath_allocator_capture cr(stack.result);
  8252. double r = 0;
  8253. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_all);
  8254. for (const xpath_node* it = ns.begin(); it != ns.end(); ++it)
  8255. {
  8256. xpath_allocator_capture cri(stack.result);
  8257. r += convert_string_to_number(string_value(*it, stack.result).c_str());
  8258. }
  8259. return r;
  8260. }
  8261. case ast_func_floor:
  8262. {
  8263. double r = _left->eval_number(c, stack);
  8264. return r == r ? floor(r) : r;
  8265. }
  8266. case ast_func_ceiling:
  8267. {
  8268. double r = _left->eval_number(c, stack);
  8269. return r == r ? ceil(r) : r;
  8270. }
  8271. case ast_func_round:
  8272. return round_nearest_nzero(_left->eval_number(c, stack));
  8273. case ast_variable:
  8274. {
  8275. assert(_rettype == _data.variable->type());
  8276. if (_rettype == xpath_type_number)
  8277. return _data.variable->get_number();
  8278. }
  8279. // fallthrough
  8280. default:
  8281. {
  8282. switch (_rettype)
  8283. {
  8284. case xpath_type_boolean:
  8285. return eval_boolean(c, stack) ? 1 : 0;
  8286. case xpath_type_string:
  8287. {
  8288. xpath_allocator_capture cr(stack.result);
  8289. return convert_string_to_number(eval_string(c, stack).c_str());
  8290. }
  8291. case xpath_type_node_set:
  8292. {
  8293. xpath_allocator_capture cr(stack.result);
  8294. return convert_string_to_number(eval_string(c, stack).c_str());
  8295. }
  8296. default:
  8297. assert(false && "Wrong expression for return type number"); // unreachable
  8298. return 0;
  8299. }
  8300. }
  8301. }
  8302. }
  8303. xpath_string eval_string_concat(const xpath_context& c, const xpath_stack& stack)
  8304. {
  8305. assert(_type == ast_func_concat);
  8306. xpath_allocator_capture ct(stack.temp);
  8307. // count the string number
  8308. size_t count = 1;
  8309. for (xpath_ast_node* nc = _right; nc; nc = nc->_next) count++;
  8310. // allocate a buffer for temporary string objects
  8311. xpath_string* buffer = static_cast<xpath_string*>(stack.temp->allocate(count * sizeof(xpath_string)));
  8312. if (!buffer) return xpath_string();
  8313. // evaluate all strings to temporary stack
  8314. xpath_stack swapped_stack = {stack.temp, stack.result};
  8315. buffer[0] = _left->eval_string(c, swapped_stack);
  8316. size_t pos = 1;
  8317. for (xpath_ast_node* n = _right; n; n = n->_next, ++pos) buffer[pos] = n->eval_string(c, swapped_stack);
  8318. assert(pos == count);
  8319. // get total length
  8320. size_t length = 0;
  8321. for (size_t i = 0; i < count; ++i) length += buffer[i].length();
  8322. // create final string
  8323. char_t* result = static_cast<char_t*>(stack.result->allocate((length + 1) * sizeof(char_t)));
  8324. if (!result) return xpath_string();
  8325. char_t* ri = result;
  8326. for (size_t j = 0; j < count; ++j)
  8327. for (const char_t* bi = buffer[j].c_str(); *bi; ++bi)
  8328. *ri++ = *bi;
  8329. *ri = 0;
  8330. return xpath_string::from_heap_preallocated(result, ri);
  8331. }
  8332. xpath_string eval_string(const xpath_context& c, const xpath_stack& stack)
  8333. {
  8334. switch (_type)
  8335. {
  8336. case ast_string_constant:
  8337. return xpath_string::from_const(_data.string);
  8338. case ast_func_local_name_0:
  8339. {
  8340. xpath_node na = c.n;
  8341. return xpath_string::from_const(local_name(na));
  8342. }
  8343. case ast_func_local_name_1:
  8344. {
  8345. xpath_allocator_capture cr(stack.result);
  8346. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
  8347. xpath_node na = ns.first();
  8348. return xpath_string::from_const(local_name(na));
  8349. }
  8350. case ast_func_name_0:
  8351. {
  8352. xpath_node na = c.n;
  8353. return xpath_string::from_const(qualified_name(na));
  8354. }
  8355. case ast_func_name_1:
  8356. {
  8357. xpath_allocator_capture cr(stack.result);
  8358. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
  8359. xpath_node na = ns.first();
  8360. return xpath_string::from_const(qualified_name(na));
  8361. }
  8362. case ast_func_namespace_uri_0:
  8363. {
  8364. xpath_node na = c.n;
  8365. return xpath_string::from_const(namespace_uri(na));
  8366. }
  8367. case ast_func_namespace_uri_1:
  8368. {
  8369. xpath_allocator_capture cr(stack.result);
  8370. xpath_node_set_raw ns = _left->eval_node_set(c, stack, nodeset_eval_first);
  8371. xpath_node na = ns.first();
  8372. return xpath_string::from_const(namespace_uri(na));
  8373. }
  8374. case ast_func_string_0:
  8375. return string_value(c.n, stack.result);
  8376. case ast_func_string_1:
  8377. return _left->eval_string(c, stack);
  8378. case ast_func_concat:
  8379. return eval_string_concat(c, stack);
  8380. case ast_func_substring_before:
  8381. {
  8382. xpath_allocator_capture cr(stack.temp);
  8383. xpath_stack swapped_stack = {stack.temp, stack.result};
  8384. xpath_string s = _left->eval_string(c, swapped_stack);
  8385. xpath_string p = _right->eval_string(c, swapped_stack);
  8386. const char_t* pos = find_substring(s.c_str(), p.c_str());
  8387. return pos ? xpath_string::from_heap(s.c_str(), pos, stack.result) : xpath_string();
  8388. }
  8389. case ast_func_substring_after:
  8390. {
  8391. xpath_allocator_capture cr(stack.temp);
  8392. xpath_stack swapped_stack = {stack.temp, stack.result};
  8393. xpath_string s = _left->eval_string(c, swapped_stack);
  8394. xpath_string p = _right->eval_string(c, swapped_stack);
  8395. const char_t* pos = find_substring(s.c_str(), p.c_str());
  8396. if (!pos) return xpath_string();
  8397. const char_t* rbegin = pos + p.length();
  8398. const char_t* rend = s.c_str() + s.length();
  8399. return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin);
  8400. }
  8401. case ast_func_substring_2:
  8402. {
  8403. xpath_allocator_capture cr(stack.temp);
  8404. xpath_stack swapped_stack = {stack.temp, stack.result};
  8405. xpath_string s = _left->eval_string(c, swapped_stack);
  8406. size_t s_length = s.length();
  8407. double first = round_nearest(_right->eval_number(c, stack));
  8408. if (is_nan(first)) return xpath_string(); // NaN
  8409. else if (first >= s_length + 1) return xpath_string();
  8410. size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
  8411. assert(1 <= pos && pos <= s_length + 1);
  8412. const char_t* rbegin = s.c_str() + (pos - 1);
  8413. const char_t* rend = s.c_str() + s.length();
  8414. return s.uses_heap() ? xpath_string::from_heap(rbegin, rend, stack.result) : xpath_string::from_const(rbegin);
  8415. }
  8416. case ast_func_substring_3:
  8417. {
  8418. xpath_allocator_capture cr(stack.temp);
  8419. xpath_stack swapped_stack = {stack.temp, stack.result};
  8420. xpath_string s = _left->eval_string(c, swapped_stack);
  8421. size_t s_length = s.length();
  8422. double first = round_nearest(_right->eval_number(c, stack));
  8423. double last = first + round_nearest(_right->_next->eval_number(c, stack));
  8424. if (is_nan(first) || is_nan(last)) return xpath_string();
  8425. else if (first >= s_length + 1) return xpath_string();
  8426. else if (first >= last) return xpath_string();
  8427. else if (last < 1) return xpath_string();
  8428. size_t pos = first < 1 ? 1 : static_cast<size_t>(first);
  8429. size_t end = last >= s_length + 1 ? s_length + 1 : static_cast<size_t>(last);
  8430. assert(1 <= pos && pos <= end && end <= s_length + 1);
  8431. const char_t* rbegin = s.c_str() + (pos - 1);
  8432. const char_t* rend = s.c_str() + (end - 1);
  8433. return (end == s_length + 1 && !s.uses_heap()) ? xpath_string::from_const(rbegin) : xpath_string::from_heap(rbegin, rend, stack.result);
  8434. }
  8435. case ast_func_normalize_space_0:
  8436. {
  8437. xpath_string s = string_value(c.n, stack.result);
  8438. char_t* begin = s.data(stack.result);
  8439. if (!begin) return xpath_string();
  8440. char_t* end = normalize_space(begin);
  8441. return xpath_string::from_heap_preallocated(begin, end);
  8442. }
  8443. case ast_func_normalize_space_1:
  8444. {
  8445. xpath_string s = _left->eval_string(c, stack);
  8446. char_t* begin = s.data(stack.result);
  8447. if (!begin) return xpath_string();
  8448. char_t* end = normalize_space(begin);
  8449. return xpath_string::from_heap_preallocated(begin, end);
  8450. }
  8451. case ast_func_translate:
  8452. {
  8453. xpath_allocator_capture cr(stack.temp);
  8454. xpath_stack swapped_stack = {stack.temp, stack.result};
  8455. xpath_string s = _left->eval_string(c, stack);
  8456. xpath_string from = _right->eval_string(c, swapped_stack);
  8457. xpath_string to = _right->_next->eval_string(c, swapped_stack);
  8458. char_t* begin = s.data(stack.result);
  8459. if (!begin) return xpath_string();
  8460. char_t* end = translate(begin, from.c_str(), to.c_str(), to.length());
  8461. return xpath_string::from_heap_preallocated(begin, end);
  8462. }
  8463. case ast_opt_translate_table:
  8464. {
  8465. xpath_string s = _left->eval_string(c, stack);
  8466. char_t* begin = s.data(stack.result);
  8467. if (!begin) return xpath_string();
  8468. char_t* end = translate_table(begin, _data.table);
  8469. return xpath_string::from_heap_preallocated(begin, end);
  8470. }
  8471. case ast_variable:
  8472. {
  8473. assert(_rettype == _data.variable->type());
  8474. if (_rettype == xpath_type_string)
  8475. return xpath_string::from_const(_data.variable->get_string());
  8476. }
  8477. // fallthrough
  8478. default:
  8479. {
  8480. switch (_rettype)
  8481. {
  8482. case xpath_type_boolean:
  8483. return xpath_string::from_const(eval_boolean(c, stack) ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
  8484. case xpath_type_number:
  8485. return convert_number_to_string(eval_number(c, stack), stack.result);
  8486. case xpath_type_node_set:
  8487. {
  8488. xpath_allocator_capture cr(stack.temp);
  8489. xpath_stack swapped_stack = {stack.temp, stack.result};
  8490. xpath_node_set_raw ns = eval_node_set(c, swapped_stack, nodeset_eval_first);
  8491. return ns.empty() ? xpath_string() : string_value(ns.first(), stack.result);
  8492. }
  8493. default:
  8494. assert(false && "Wrong expression for return type string"); // unreachable
  8495. return xpath_string();
  8496. }
  8497. }
  8498. }
  8499. }
  8500. xpath_node_set_raw eval_node_set(const xpath_context& c, const xpath_stack& stack, nodeset_eval_t eval)
  8501. {
  8502. switch (_type)
  8503. {
  8504. case ast_op_union:
  8505. {
  8506. xpath_allocator_capture cr(stack.temp);
  8507. xpath_stack swapped_stack = {stack.temp, stack.result};
  8508. xpath_node_set_raw ls = _left->eval_node_set(c, stack, eval);
  8509. xpath_node_set_raw rs = _right->eval_node_set(c, swapped_stack, eval);
  8510. // we can optimize merging two sorted sets, but this is a very rare operation, so don't bother
  8511. ls.set_type(xpath_node_set::type_unsorted);
  8512. ls.append(rs.begin(), rs.end(), stack.result);
  8513. ls.remove_duplicates(stack.temp);
  8514. return ls;
  8515. }
  8516. case ast_filter:
  8517. {
  8518. xpath_node_set_raw set = _left->eval_node_set(c, stack, _test == predicate_constant_one ? nodeset_eval_first : nodeset_eval_all);
  8519. // either expression is a number or it contains position() call; sort by document order
  8520. if (_test != predicate_posinv) set.sort_do();
  8521. bool once = eval_once(set.type(), eval);
  8522. apply_predicate(set, 0, stack, once);
  8523. return set;
  8524. }
  8525. case ast_func_id:
  8526. return xpath_node_set_raw();
  8527. case ast_step:
  8528. {
  8529. switch (_axis)
  8530. {
  8531. case axis_ancestor:
  8532. return step_do(c, stack, eval, axis_to_type<axis_ancestor>());
  8533. case axis_ancestor_or_self:
  8534. return step_do(c, stack, eval, axis_to_type<axis_ancestor_or_self>());
  8535. case axis_attribute:
  8536. return step_do(c, stack, eval, axis_to_type<axis_attribute>());
  8537. case axis_child:
  8538. return step_do(c, stack, eval, axis_to_type<axis_child>());
  8539. case axis_descendant:
  8540. return step_do(c, stack, eval, axis_to_type<axis_descendant>());
  8541. case axis_descendant_or_self:
  8542. return step_do(c, stack, eval, axis_to_type<axis_descendant_or_self>());
  8543. case axis_following:
  8544. return step_do(c, stack, eval, axis_to_type<axis_following>());
  8545. case axis_following_sibling:
  8546. return step_do(c, stack, eval, axis_to_type<axis_following_sibling>());
  8547. case axis_namespace:
  8548. // namespaced axis is not supported
  8549. return xpath_node_set_raw();
  8550. case axis_parent:
  8551. return step_do(c, stack, eval, axis_to_type<axis_parent>());
  8552. case axis_preceding:
  8553. return step_do(c, stack, eval, axis_to_type<axis_preceding>());
  8554. case axis_preceding_sibling:
  8555. return step_do(c, stack, eval, axis_to_type<axis_preceding_sibling>());
  8556. case axis_self:
  8557. return step_do(c, stack, eval, axis_to_type<axis_self>());
  8558. default:
  8559. assert(false && "Unknown axis"); // unreachable
  8560. return xpath_node_set_raw();
  8561. }
  8562. }
  8563. case ast_step_root:
  8564. {
  8565. assert(!_right); // root step can't have any predicates
  8566. xpath_node_set_raw ns;
  8567. ns.set_type(xpath_node_set::type_sorted);
  8568. if (c.n.node()) ns.push_back(c.n.node().root(), stack.result);
  8569. else if (c.n.attribute()) ns.push_back(c.n.parent().root(), stack.result);
  8570. return ns;
  8571. }
  8572. case ast_variable:
  8573. {
  8574. assert(_rettype == _data.variable->type());
  8575. if (_rettype == xpath_type_node_set)
  8576. {
  8577. const xpath_node_set& s = _data.variable->get_node_set();
  8578. xpath_node_set_raw ns;
  8579. ns.set_type(s.type());
  8580. ns.append(s.begin(), s.end(), stack.result);
  8581. return ns;
  8582. }
  8583. }
  8584. // fallthrough
  8585. default:
  8586. assert(false && "Wrong expression for return type node set"); // unreachable
  8587. return xpath_node_set_raw();
  8588. }
  8589. }
  8590. void optimize(xpath_allocator* alloc)
  8591. {
  8592. if (_left)
  8593. _left->optimize(alloc);
  8594. if (_right)
  8595. _right->optimize(alloc);
  8596. if (_next)
  8597. _next->optimize(alloc);
  8598. // coverity[var_deref_model]
  8599. optimize_self(alloc);
  8600. }
  8601. void optimize_self(xpath_allocator* alloc)
  8602. {
  8603. // Rewrite [position()=expr] with [expr]
  8604. // Note that this step has to go before classification to recognize [position()=1]
  8605. if ((_type == ast_filter || _type == ast_predicate) &&
  8606. _right && // workaround for clang static analyzer (_right is never null for ast_filter/ast_predicate)
  8607. _right->_type == ast_op_equal && _right->_left->_type == ast_func_position && _right->_right->_rettype == xpath_type_number)
  8608. {
  8609. _right = _right->_right;
  8610. }
  8611. // Classify filter/predicate ops to perform various optimizations during evaluation
  8612. if ((_type == ast_filter || _type == ast_predicate) && _right) // workaround for clang static analyzer (_right is never null for ast_filter/ast_predicate)
  8613. {
  8614. assert(_test == predicate_default);
  8615. if (_right->_type == ast_number_constant && _right->_data.number == 1.0)
  8616. _test = predicate_constant_one;
  8617. else if (_right->_rettype == xpath_type_number && (_right->_type == ast_number_constant || _right->_type == ast_variable || _right->_type == ast_func_last))
  8618. _test = predicate_constant;
  8619. else if (_right->_rettype != xpath_type_number && _right->is_posinv_expr())
  8620. _test = predicate_posinv;
  8621. }
  8622. // Rewrite descendant-or-self::node()/child::foo with descendant::foo
  8623. // The former is a full form of //foo, the latter is much faster since it executes the node test immediately
  8624. // Do a similar kind of rewrite for self/descendant/descendant-or-self axes
  8625. // Note that we only rewrite positionally invariant steps (//foo[1] != /descendant::foo[1])
  8626. if (_type == ast_step && (_axis == axis_child || _axis == axis_self || _axis == axis_descendant || _axis == axis_descendant_or_self) &&
  8627. _left && _left->_type == ast_step && _left->_axis == axis_descendant_or_self && _left->_test == nodetest_type_node && !_left->_right &&
  8628. is_posinv_step())
  8629. {
  8630. if (_axis == axis_child || _axis == axis_descendant)
  8631. _axis = axis_descendant;
  8632. else
  8633. _axis = axis_descendant_or_self;
  8634. _left = _left->_left;
  8635. }
  8636. // Use optimized lookup table implementation for translate() with constant arguments
  8637. if (_type == ast_func_translate &&
  8638. _right && // workaround for clang static analyzer (_right is never null for ast_func_translate)
  8639. _right->_type == ast_string_constant && _right->_next->_type == ast_string_constant)
  8640. {
  8641. unsigned char* table = translate_table_generate(alloc, _right->_data.string, _right->_next->_data.string);
  8642. if (table)
  8643. {
  8644. _type = ast_opt_translate_table;
  8645. _data.table = table;
  8646. }
  8647. }
  8648. // Use optimized path for @attr = 'value' or @attr = $value
  8649. if (_type == ast_op_equal &&
  8650. _left && _right && // workaround for clang static analyzer and Coverity (_left and _right are never null for ast_op_equal)
  8651. // coverity[mixed_enums]
  8652. _left->_type == ast_step && _left->_axis == axis_attribute && _left->_test == nodetest_name && !_left->_left && !_left->_right &&
  8653. (_right->_type == ast_string_constant || (_right->_type == ast_variable && _right->_rettype == xpath_type_string)))
  8654. {
  8655. _type = ast_opt_compare_attribute;
  8656. }
  8657. }
  8658. bool is_posinv_expr() const
  8659. {
  8660. switch (_type)
  8661. {
  8662. case ast_func_position:
  8663. case ast_func_last:
  8664. return false;
  8665. case ast_string_constant:
  8666. case ast_number_constant:
  8667. case ast_variable:
  8668. return true;
  8669. case ast_step:
  8670. case ast_step_root:
  8671. return true;
  8672. case ast_predicate:
  8673. case ast_filter:
  8674. return true;
  8675. default:
  8676. if (_left && !_left->is_posinv_expr()) return false;
  8677. for (xpath_ast_node* n = _right; n; n = n->_next)
  8678. if (!n->is_posinv_expr()) return false;
  8679. return true;
  8680. }
  8681. }
  8682. bool is_posinv_step() const
  8683. {
  8684. assert(_type == ast_step);
  8685. for (xpath_ast_node* n = _right; n; n = n->_next)
  8686. {
  8687. assert(n->_type == ast_predicate);
  8688. if (n->_test != predicate_posinv)
  8689. return false;
  8690. }
  8691. return true;
  8692. }
  8693. xpath_value_type rettype() const
  8694. {
  8695. return static_cast<xpath_value_type>(_rettype);
  8696. }
  8697. };
  8698. struct xpath_parser
  8699. {
  8700. xpath_allocator* _alloc;
  8701. xpath_lexer _lexer;
  8702. const char_t* _query;
  8703. xpath_variable_set* _variables;
  8704. xpath_parse_result* _result;
  8705. char_t _scratch[32];
  8706. xpath_ast_node* error(const char* message)
  8707. {
  8708. _result->error = message;
  8709. _result->offset = _lexer.current_pos() - _query;
  8710. return 0;
  8711. }
  8712. xpath_ast_node* error_oom()
  8713. {
  8714. assert(_alloc->_error);
  8715. *_alloc->_error = true;
  8716. return 0;
  8717. }
  8718. void* alloc_node()
  8719. {
  8720. return _alloc->allocate(sizeof(xpath_ast_node));
  8721. }
  8722. xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, const char_t* value)
  8723. {
  8724. void* memory = alloc_node();
  8725. return memory ? new (memory) xpath_ast_node(type, rettype, value) : 0;
  8726. }
  8727. xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, double value)
  8728. {
  8729. void* memory = alloc_node();
  8730. return memory ? new (memory) xpath_ast_node(type, rettype, value) : 0;
  8731. }
  8732. xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, xpath_variable* value)
  8733. {
  8734. void* memory = alloc_node();
  8735. return memory ? new (memory) xpath_ast_node(type, rettype, value) : 0;
  8736. }
  8737. xpath_ast_node* alloc_node(ast_type_t type, xpath_value_type rettype, xpath_ast_node* left = 0, xpath_ast_node* right = 0)
  8738. {
  8739. void* memory = alloc_node();
  8740. return memory ? new (memory) xpath_ast_node(type, rettype, left, right) : 0;
  8741. }
  8742. xpath_ast_node* alloc_node(ast_type_t type, xpath_ast_node* left, axis_t axis, nodetest_t test, const char_t* contents)
  8743. {
  8744. void* memory = alloc_node();
  8745. return memory ? new (memory) xpath_ast_node(type, left, axis, test, contents) : 0;
  8746. }
  8747. xpath_ast_node* alloc_node(ast_type_t type, xpath_ast_node* left, xpath_ast_node* right, predicate_t test)
  8748. {
  8749. void* memory = alloc_node();
  8750. return memory ? new (memory) xpath_ast_node(type, left, right, test) : 0;
  8751. }
  8752. const char_t* alloc_string(const xpath_lexer_string& value)
  8753. {
  8754. if (!value.begin)
  8755. return PUGIXML_TEXT("");
  8756. size_t length = static_cast<size_t>(value.end - value.begin);
  8757. char_t* c = static_cast<char_t*>(_alloc->allocate((length + 1) * sizeof(char_t)));
  8758. if (!c) return 0;
  8759. memcpy(c, value.begin, length * sizeof(char_t));
  8760. c[length] = 0;
  8761. return c;
  8762. }
  8763. xpath_ast_node* parse_function(const xpath_lexer_string& name, size_t argc, xpath_ast_node* args[2])
  8764. {
  8765. switch (name.begin[0])
  8766. {
  8767. case 'b':
  8768. if (name == PUGIXML_TEXT("boolean") && argc == 1)
  8769. return alloc_node(ast_func_boolean, xpath_type_boolean, args[0]);
  8770. break;
  8771. case 'c':
  8772. if (name == PUGIXML_TEXT("count") && argc == 1)
  8773. {
  8774. if (args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
  8775. return alloc_node(ast_func_count, xpath_type_number, args[0]);
  8776. }
  8777. else if (name == PUGIXML_TEXT("contains") && argc == 2)
  8778. return alloc_node(ast_func_contains, xpath_type_boolean, args[0], args[1]);
  8779. else if (name == PUGIXML_TEXT("concat") && argc >= 2)
  8780. return alloc_node(ast_func_concat, xpath_type_string, args[0], args[1]);
  8781. else if (name == PUGIXML_TEXT("ceiling") && argc == 1)
  8782. return alloc_node(ast_func_ceiling, xpath_type_number, args[0]);
  8783. break;
  8784. case 'f':
  8785. if (name == PUGIXML_TEXT("false") && argc == 0)
  8786. return alloc_node(ast_func_false, xpath_type_boolean);
  8787. else if (name == PUGIXML_TEXT("floor") && argc == 1)
  8788. return alloc_node(ast_func_floor, xpath_type_number, args[0]);
  8789. break;
  8790. case 'i':
  8791. if (name == PUGIXML_TEXT("id") && argc == 1)
  8792. return alloc_node(ast_func_id, xpath_type_node_set, args[0]);
  8793. break;
  8794. case 'l':
  8795. if (name == PUGIXML_TEXT("last") && argc == 0)
  8796. return alloc_node(ast_func_last, xpath_type_number);
  8797. else if (name == PUGIXML_TEXT("lang") && argc == 1)
  8798. return alloc_node(ast_func_lang, xpath_type_boolean, args[0]);
  8799. else if (name == PUGIXML_TEXT("local-name") && argc <= 1)
  8800. {
  8801. if (argc == 1 && args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
  8802. return alloc_node(argc == 0 ? ast_func_local_name_0 : ast_func_local_name_1, xpath_type_string, args[0]);
  8803. }
  8804. break;
  8805. case 'n':
  8806. if (name == PUGIXML_TEXT("name") && argc <= 1)
  8807. {
  8808. if (argc == 1 && args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
  8809. return alloc_node(argc == 0 ? ast_func_name_0 : ast_func_name_1, xpath_type_string, args[0]);
  8810. }
  8811. else if (name == PUGIXML_TEXT("namespace-uri") && argc <= 1)
  8812. {
  8813. if (argc == 1 && args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
  8814. return alloc_node(argc == 0 ? ast_func_namespace_uri_0 : ast_func_namespace_uri_1, xpath_type_string, args[0]);
  8815. }
  8816. else if (name == PUGIXML_TEXT("normalize-space") && argc <= 1)
  8817. return alloc_node(argc == 0 ? ast_func_normalize_space_0 : ast_func_normalize_space_1, xpath_type_string, args[0], args[1]);
  8818. else if (name == PUGIXML_TEXT("not") && argc == 1)
  8819. return alloc_node(ast_func_not, xpath_type_boolean, args[0]);
  8820. else if (name == PUGIXML_TEXT("number") && argc <= 1)
  8821. return alloc_node(argc == 0 ? ast_func_number_0 : ast_func_number_1, xpath_type_number, args[0]);
  8822. break;
  8823. case 'p':
  8824. if (name == PUGIXML_TEXT("position") && argc == 0)
  8825. return alloc_node(ast_func_position, xpath_type_number);
  8826. break;
  8827. case 'r':
  8828. if (name == PUGIXML_TEXT("round") && argc == 1)
  8829. return alloc_node(ast_func_round, xpath_type_number, args[0]);
  8830. break;
  8831. case 's':
  8832. if (name == PUGIXML_TEXT("string") && argc <= 1)
  8833. return alloc_node(argc == 0 ? ast_func_string_0 : ast_func_string_1, xpath_type_string, args[0]);
  8834. else if (name == PUGIXML_TEXT("string-length") && argc <= 1)
  8835. return alloc_node(argc == 0 ? ast_func_string_length_0 : ast_func_string_length_1, xpath_type_number, args[0]);
  8836. else if (name == PUGIXML_TEXT("starts-with") && argc == 2)
  8837. return alloc_node(ast_func_starts_with, xpath_type_boolean, args[0], args[1]);
  8838. else if (name == PUGIXML_TEXT("substring-before") && argc == 2)
  8839. return alloc_node(ast_func_substring_before, xpath_type_string, args[0], args[1]);
  8840. else if (name == PUGIXML_TEXT("substring-after") && argc == 2)
  8841. return alloc_node(ast_func_substring_after, xpath_type_string, args[0], args[1]);
  8842. else if (name == PUGIXML_TEXT("substring") && (argc == 2 || argc == 3))
  8843. return alloc_node(argc == 2 ? ast_func_substring_2 : ast_func_substring_3, xpath_type_string, args[0], args[1]);
  8844. else if (name == PUGIXML_TEXT("sum") && argc == 1)
  8845. {
  8846. if (args[0]->rettype() != xpath_type_node_set) return error("Function has to be applied to node set");
  8847. return alloc_node(ast_func_sum, xpath_type_number, args[0]);
  8848. }
  8849. break;
  8850. case 't':
  8851. if (name == PUGIXML_TEXT("translate") && argc == 3)
  8852. return alloc_node(ast_func_translate, xpath_type_string, args[0], args[1]);
  8853. else if (name == PUGIXML_TEXT("true") && argc == 0)
  8854. return alloc_node(ast_func_true, xpath_type_boolean);
  8855. break;
  8856. default:
  8857. break;
  8858. }
  8859. return error("Unrecognized function or wrong parameter count");
  8860. }
  8861. axis_t parse_axis_name(const xpath_lexer_string& name, bool& specified)
  8862. {
  8863. specified = true;
  8864. switch (name.begin[0])
  8865. {
  8866. case 'a':
  8867. if (name == PUGIXML_TEXT("ancestor"))
  8868. return axis_ancestor;
  8869. else if (name == PUGIXML_TEXT("ancestor-or-self"))
  8870. return axis_ancestor_or_self;
  8871. else if (name == PUGIXML_TEXT("attribute"))
  8872. return axis_attribute;
  8873. break;
  8874. case 'c':
  8875. if (name == PUGIXML_TEXT("child"))
  8876. return axis_child;
  8877. break;
  8878. case 'd':
  8879. if (name == PUGIXML_TEXT("descendant"))
  8880. return axis_descendant;
  8881. else if (name == PUGIXML_TEXT("descendant-or-self"))
  8882. return axis_descendant_or_self;
  8883. break;
  8884. case 'f':
  8885. if (name == PUGIXML_TEXT("following"))
  8886. return axis_following;
  8887. else if (name == PUGIXML_TEXT("following-sibling"))
  8888. return axis_following_sibling;
  8889. break;
  8890. case 'n':
  8891. if (name == PUGIXML_TEXT("namespace"))
  8892. return axis_namespace;
  8893. break;
  8894. case 'p':
  8895. if (name == PUGIXML_TEXT("parent"))
  8896. return axis_parent;
  8897. else if (name == PUGIXML_TEXT("preceding"))
  8898. return axis_preceding;
  8899. else if (name == PUGIXML_TEXT("preceding-sibling"))
  8900. return axis_preceding_sibling;
  8901. break;
  8902. case 's':
  8903. if (name == PUGIXML_TEXT("self"))
  8904. return axis_self;
  8905. break;
  8906. default:
  8907. break;
  8908. }
  8909. specified = false;
  8910. return axis_child;
  8911. }
  8912. nodetest_t parse_node_test_type(const xpath_lexer_string& name)
  8913. {
  8914. switch (name.begin[0])
  8915. {
  8916. case 'c':
  8917. if (name == PUGIXML_TEXT("comment"))
  8918. return nodetest_type_comment;
  8919. break;
  8920. case 'n':
  8921. if (name == PUGIXML_TEXT("node"))
  8922. return nodetest_type_node;
  8923. break;
  8924. case 'p':
  8925. if (name == PUGIXML_TEXT("processing-instruction"))
  8926. return nodetest_type_pi;
  8927. break;
  8928. case 't':
  8929. if (name == PUGIXML_TEXT("text"))
  8930. return nodetest_type_text;
  8931. break;
  8932. default:
  8933. break;
  8934. }
  8935. return nodetest_none;
  8936. }
  8937. // PrimaryExpr ::= VariableReference | '(' Expr ')' | Literal | Number | FunctionCall
  8938. xpath_ast_node* parse_primary_expression()
  8939. {
  8940. switch (_lexer.current())
  8941. {
  8942. case lex_var_ref:
  8943. {
  8944. xpath_lexer_string name = _lexer.contents();
  8945. if (!_variables)
  8946. return error("Unknown variable: variable set is not provided");
  8947. xpath_variable* var = 0;
  8948. if (!get_variable_scratch(_scratch, _variables, name.begin, name.end, &var))
  8949. return error_oom();
  8950. if (!var)
  8951. return error("Unknown variable: variable set does not contain the given name");
  8952. _lexer.next();
  8953. return alloc_node(ast_variable, var->type(), var);
  8954. }
  8955. case lex_open_brace:
  8956. {
  8957. _lexer.next();
  8958. xpath_ast_node* n = parse_expression();
  8959. if (!n) return 0;
  8960. if (_lexer.current() != lex_close_brace)
  8961. return error("Expected ')' to match an opening '('");
  8962. _lexer.next();
  8963. return n;
  8964. }
  8965. case lex_quoted_string:
  8966. {
  8967. const char_t* value = alloc_string(_lexer.contents());
  8968. if (!value) return 0;
  8969. _lexer.next();
  8970. return alloc_node(ast_string_constant, xpath_type_string, value);
  8971. }
  8972. case lex_number:
  8973. {
  8974. double value = 0;
  8975. if (!convert_string_to_number_scratch(_scratch, _lexer.contents().begin, _lexer.contents().end, &value))
  8976. return error_oom();
  8977. _lexer.next();
  8978. return alloc_node(ast_number_constant, xpath_type_number, value);
  8979. }
  8980. case lex_string:
  8981. {
  8982. xpath_ast_node* args[2] = {0};
  8983. size_t argc = 0;
  8984. xpath_lexer_string function = _lexer.contents();
  8985. _lexer.next();
  8986. xpath_ast_node* last_arg = 0;
  8987. if (_lexer.current() != lex_open_brace)
  8988. return error("Unrecognized function call");
  8989. _lexer.next();
  8990. while (_lexer.current() != lex_close_brace)
  8991. {
  8992. if (argc > 0)
  8993. {
  8994. if (_lexer.current() != lex_comma)
  8995. return error("No comma between function arguments");
  8996. _lexer.next();
  8997. }
  8998. xpath_ast_node* n = parse_expression();
  8999. if (!n) return 0;
  9000. if (argc < 2) args[argc] = n;
  9001. else last_arg->set_next(n);
  9002. argc++;
  9003. last_arg = n;
  9004. }
  9005. _lexer.next();
  9006. return parse_function(function, argc, args);
  9007. }
  9008. default:
  9009. return error("Unrecognizable primary expression");
  9010. }
  9011. }
  9012. // FilterExpr ::= PrimaryExpr | FilterExpr Predicate
  9013. // Predicate ::= '[' PredicateExpr ']'
  9014. // PredicateExpr ::= Expr
  9015. xpath_ast_node* parse_filter_expression()
  9016. {
  9017. xpath_ast_node* n = parse_primary_expression();
  9018. if (!n) return 0;
  9019. while (_lexer.current() == lex_open_square_brace)
  9020. {
  9021. _lexer.next();
  9022. if (n->rettype() != xpath_type_node_set)
  9023. return error("Predicate has to be applied to node set");
  9024. xpath_ast_node* expr = parse_expression();
  9025. if (!expr) return 0;
  9026. n = alloc_node(ast_filter, n, expr, predicate_default);
  9027. if (!n) return 0;
  9028. if (_lexer.current() != lex_close_square_brace)
  9029. return error("Expected ']' to match an opening '['");
  9030. _lexer.next();
  9031. }
  9032. return n;
  9033. }
  9034. // Step ::= AxisSpecifier NodeTest Predicate* | AbbreviatedStep
  9035. // AxisSpecifier ::= AxisName '::' | '@'?
  9036. // NodeTest ::= NameTest | NodeType '(' ')' | 'processing-instruction' '(' Literal ')'
  9037. // NameTest ::= '*' | NCName ':' '*' | QName
  9038. // AbbreviatedStep ::= '.' | '..'
  9039. xpath_ast_node* parse_step(xpath_ast_node* set)
  9040. {
  9041. if (set && set->rettype() != xpath_type_node_set)
  9042. return error("Step has to be applied to node set");
  9043. bool axis_specified = false;
  9044. axis_t axis = axis_child; // implied child axis
  9045. if (_lexer.current() == lex_axis_attribute)
  9046. {
  9047. axis = axis_attribute;
  9048. axis_specified = true;
  9049. _lexer.next();
  9050. }
  9051. else if (_lexer.current() == lex_dot)
  9052. {
  9053. _lexer.next();
  9054. if (_lexer.current() == lex_open_square_brace)
  9055. return error("Predicates are not allowed after an abbreviated step");
  9056. return alloc_node(ast_step, set, axis_self, nodetest_type_node, 0);
  9057. }
  9058. else if (_lexer.current() == lex_double_dot)
  9059. {
  9060. _lexer.next();
  9061. if (_lexer.current() == lex_open_square_brace)
  9062. return error("Predicates are not allowed after an abbreviated step");
  9063. return alloc_node(ast_step, set, axis_parent, nodetest_type_node, 0);
  9064. }
  9065. nodetest_t nt_type = nodetest_none;
  9066. xpath_lexer_string nt_name;
  9067. if (_lexer.current() == lex_string)
  9068. {
  9069. // node name test
  9070. nt_name = _lexer.contents();
  9071. _lexer.next();
  9072. // was it an axis name?
  9073. if (_lexer.current() == lex_double_colon)
  9074. {
  9075. // parse axis name
  9076. if (axis_specified)
  9077. return error("Two axis specifiers in one step");
  9078. axis = parse_axis_name(nt_name, axis_specified);
  9079. if (!axis_specified)
  9080. return error("Unknown axis");
  9081. // read actual node test
  9082. _lexer.next();
  9083. if (_lexer.current() == lex_multiply)
  9084. {
  9085. nt_type = nodetest_all;
  9086. nt_name = xpath_lexer_string();
  9087. _lexer.next();
  9088. }
  9089. else if (_lexer.current() == lex_string)
  9090. {
  9091. nt_name = _lexer.contents();
  9092. _lexer.next();
  9093. }
  9094. else
  9095. {
  9096. return error("Unrecognized node test");
  9097. }
  9098. }
  9099. if (nt_type == nodetest_none)
  9100. {
  9101. // node type test or processing-instruction
  9102. if (_lexer.current() == lex_open_brace)
  9103. {
  9104. _lexer.next();
  9105. if (_lexer.current() == lex_close_brace)
  9106. {
  9107. _lexer.next();
  9108. nt_type = parse_node_test_type(nt_name);
  9109. if (nt_type == nodetest_none)
  9110. return error("Unrecognized node type");
  9111. nt_name = xpath_lexer_string();
  9112. }
  9113. else if (nt_name == PUGIXML_TEXT("processing-instruction"))
  9114. {
  9115. if (_lexer.current() != lex_quoted_string)
  9116. return error("Only literals are allowed as arguments to processing-instruction()");
  9117. nt_type = nodetest_pi;
  9118. nt_name = _lexer.contents();
  9119. _lexer.next();
  9120. if (_lexer.current() != lex_close_brace)
  9121. return error("Unmatched brace near processing-instruction()");
  9122. _lexer.next();
  9123. }
  9124. else
  9125. {
  9126. return error("Unmatched brace near node type test");
  9127. }
  9128. }
  9129. // QName or NCName:*
  9130. else
  9131. {
  9132. if (nt_name.end - nt_name.begin > 2 && nt_name.end[-2] == ':' && nt_name.end[-1] == '*') // NCName:*
  9133. {
  9134. nt_name.end--; // erase *
  9135. nt_type = nodetest_all_in_namespace;
  9136. }
  9137. else
  9138. {
  9139. nt_type = nodetest_name;
  9140. }
  9141. }
  9142. }
  9143. }
  9144. else if (_lexer.current() == lex_multiply)
  9145. {
  9146. nt_type = nodetest_all;
  9147. _lexer.next();
  9148. }
  9149. else
  9150. {
  9151. return error("Unrecognized node test");
  9152. }
  9153. const char_t* nt_name_copy = alloc_string(nt_name);
  9154. if (!nt_name_copy) return 0;
  9155. xpath_ast_node* n = alloc_node(ast_step, set, axis, nt_type, nt_name_copy);
  9156. if (!n) return 0;
  9157. xpath_ast_node* last = 0;
  9158. while (_lexer.current() == lex_open_square_brace)
  9159. {
  9160. _lexer.next();
  9161. xpath_ast_node* expr = parse_expression();
  9162. if (!expr) return 0;
  9163. xpath_ast_node* pred = alloc_node(ast_predicate, 0, expr, predicate_default);
  9164. if (!pred) return 0;
  9165. if (_lexer.current() != lex_close_square_brace)
  9166. return error("Expected ']' to match an opening '['");
  9167. _lexer.next();
  9168. if (last) last->set_next(pred);
  9169. else n->set_right(pred);
  9170. last = pred;
  9171. }
  9172. return n;
  9173. }
  9174. // RelativeLocationPath ::= Step | RelativeLocationPath '/' Step | RelativeLocationPath '//' Step
  9175. xpath_ast_node* parse_relative_location_path(xpath_ast_node* set)
  9176. {
  9177. xpath_ast_node* n = parse_step(set);
  9178. if (!n) return 0;
  9179. while (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
  9180. {
  9181. lexeme_t l = _lexer.current();
  9182. _lexer.next();
  9183. if (l == lex_double_slash)
  9184. {
  9185. n = alloc_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  9186. if (!n) return 0;
  9187. }
  9188. n = parse_step(n);
  9189. if (!n) return 0;
  9190. }
  9191. return n;
  9192. }
  9193. // LocationPath ::= RelativeLocationPath | AbsoluteLocationPath
  9194. // AbsoluteLocationPath ::= '/' RelativeLocationPath? | '//' RelativeLocationPath
  9195. xpath_ast_node* parse_location_path()
  9196. {
  9197. if (_lexer.current() == lex_slash)
  9198. {
  9199. _lexer.next();
  9200. xpath_ast_node* n = alloc_node(ast_step_root, xpath_type_node_set);
  9201. if (!n) return 0;
  9202. // relative location path can start from axis_attribute, dot, double_dot, multiply and string lexemes; any other lexeme means standalone root path
  9203. lexeme_t l = _lexer.current();
  9204. if (l == lex_string || l == lex_axis_attribute || l == lex_dot || l == lex_double_dot || l == lex_multiply)
  9205. return parse_relative_location_path(n);
  9206. else
  9207. return n;
  9208. }
  9209. else if (_lexer.current() == lex_double_slash)
  9210. {
  9211. _lexer.next();
  9212. xpath_ast_node* n = alloc_node(ast_step_root, xpath_type_node_set);
  9213. if (!n) return 0;
  9214. n = alloc_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  9215. if (!n) return 0;
  9216. return parse_relative_location_path(n);
  9217. }
  9218. // 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
  9219. return parse_relative_location_path(0);
  9220. }
  9221. // PathExpr ::= LocationPath
  9222. // | FilterExpr
  9223. // | FilterExpr '/' RelativeLocationPath
  9224. // | FilterExpr '//' RelativeLocationPath
  9225. // UnionExpr ::= PathExpr | UnionExpr '|' PathExpr
  9226. // UnaryExpr ::= UnionExpr | '-' UnaryExpr
  9227. xpath_ast_node* parse_path_or_unary_expression()
  9228. {
  9229. // Clarification.
  9230. // PathExpr begins with either LocationPath or FilterExpr.
  9231. // FilterExpr begins with PrimaryExpr
  9232. // PrimaryExpr begins with '$' in case of it being a variable reference,
  9233. // '(' in case of it being an expression, string literal, number constant or
  9234. // function call.
  9235. if (_lexer.current() == lex_var_ref || _lexer.current() == lex_open_brace ||
  9236. _lexer.current() == lex_quoted_string || _lexer.current() == lex_number ||
  9237. _lexer.current() == lex_string)
  9238. {
  9239. if (_lexer.current() == lex_string)
  9240. {
  9241. // This is either a function call, or not - if not, we shall proceed with location path
  9242. const char_t* state = _lexer.state();
  9243. while (PUGI__IS_CHARTYPE(*state, ct_space)) ++state;
  9244. if (*state != '(')
  9245. return parse_location_path();
  9246. // This looks like a function call; however this still can be a node-test. Check it.
  9247. if (parse_node_test_type(_lexer.contents()) != nodetest_none)
  9248. return parse_location_path();
  9249. }
  9250. xpath_ast_node* n = parse_filter_expression();
  9251. if (!n) return 0;
  9252. if (_lexer.current() == lex_slash || _lexer.current() == lex_double_slash)
  9253. {
  9254. lexeme_t l = _lexer.current();
  9255. _lexer.next();
  9256. if (l == lex_double_slash)
  9257. {
  9258. if (n->rettype() != xpath_type_node_set)
  9259. return error("Step has to be applied to node set");
  9260. n = alloc_node(ast_step, n, axis_descendant_or_self, nodetest_type_node, 0);
  9261. if (!n) return 0;
  9262. }
  9263. // select from location path
  9264. return parse_relative_location_path(n);
  9265. }
  9266. return n;
  9267. }
  9268. else if (_lexer.current() == lex_minus)
  9269. {
  9270. _lexer.next();
  9271. // precedence 7+ - only parses union expressions
  9272. xpath_ast_node* n = parse_expression(7);
  9273. if (!n) return 0;
  9274. return alloc_node(ast_op_negate, xpath_type_number, n);
  9275. }
  9276. else
  9277. {
  9278. return parse_location_path();
  9279. }
  9280. }
  9281. struct binary_op_t
  9282. {
  9283. ast_type_t asttype;
  9284. xpath_value_type rettype;
  9285. int precedence;
  9286. binary_op_t(): asttype(ast_unknown), rettype(xpath_type_none), precedence(0)
  9287. {
  9288. }
  9289. binary_op_t(ast_type_t asttype_, xpath_value_type rettype_, int precedence_): asttype(asttype_), rettype(rettype_), precedence(precedence_)
  9290. {
  9291. }
  9292. static binary_op_t parse(xpath_lexer& lexer)
  9293. {
  9294. switch (lexer.current())
  9295. {
  9296. case lex_string:
  9297. if (lexer.contents() == PUGIXML_TEXT("or"))
  9298. return binary_op_t(ast_op_or, xpath_type_boolean, 1);
  9299. else if (lexer.contents() == PUGIXML_TEXT("and"))
  9300. return binary_op_t(ast_op_and, xpath_type_boolean, 2);
  9301. else if (lexer.contents() == PUGIXML_TEXT("div"))
  9302. return binary_op_t(ast_op_divide, xpath_type_number, 6);
  9303. else if (lexer.contents() == PUGIXML_TEXT("mod"))
  9304. return binary_op_t(ast_op_mod, xpath_type_number, 6);
  9305. else
  9306. return binary_op_t();
  9307. case lex_equal:
  9308. return binary_op_t(ast_op_equal, xpath_type_boolean, 3);
  9309. case lex_not_equal:
  9310. return binary_op_t(ast_op_not_equal, xpath_type_boolean, 3);
  9311. case lex_less:
  9312. return binary_op_t(ast_op_less, xpath_type_boolean, 4);
  9313. case lex_greater:
  9314. return binary_op_t(ast_op_greater, xpath_type_boolean, 4);
  9315. case lex_less_or_equal:
  9316. return binary_op_t(ast_op_less_or_equal, xpath_type_boolean, 4);
  9317. case lex_greater_or_equal:
  9318. return binary_op_t(ast_op_greater_or_equal, xpath_type_boolean, 4);
  9319. case lex_plus:
  9320. return binary_op_t(ast_op_add, xpath_type_number, 5);
  9321. case lex_minus:
  9322. return binary_op_t(ast_op_subtract, xpath_type_number, 5);
  9323. case lex_multiply:
  9324. return binary_op_t(ast_op_multiply, xpath_type_number, 6);
  9325. case lex_union:
  9326. return binary_op_t(ast_op_union, xpath_type_node_set, 7);
  9327. default:
  9328. return binary_op_t();
  9329. }
  9330. }
  9331. };
  9332. xpath_ast_node* parse_expression_rec(xpath_ast_node* lhs, int limit)
  9333. {
  9334. binary_op_t op = binary_op_t::parse(_lexer);
  9335. while (op.asttype != ast_unknown && op.precedence >= limit)
  9336. {
  9337. _lexer.next();
  9338. xpath_ast_node* rhs = parse_path_or_unary_expression();
  9339. if (!rhs) return 0;
  9340. binary_op_t nextop = binary_op_t::parse(_lexer);
  9341. while (nextop.asttype != ast_unknown && nextop.precedence > op.precedence)
  9342. {
  9343. rhs = parse_expression_rec(rhs, nextop.precedence);
  9344. if (!rhs) return 0;
  9345. nextop = binary_op_t::parse(_lexer);
  9346. }
  9347. if (op.asttype == ast_op_union && (lhs->rettype() != xpath_type_node_set || rhs->rettype() != xpath_type_node_set))
  9348. return error("Union operator has to be applied to node sets");
  9349. lhs = alloc_node(op.asttype, op.rettype, lhs, rhs);
  9350. if (!lhs) return 0;
  9351. op = binary_op_t::parse(_lexer);
  9352. }
  9353. return lhs;
  9354. }
  9355. // Expr ::= OrExpr
  9356. // OrExpr ::= AndExpr | OrExpr 'or' AndExpr
  9357. // AndExpr ::= EqualityExpr | AndExpr 'and' EqualityExpr
  9358. // EqualityExpr ::= RelationalExpr
  9359. // | EqualityExpr '=' RelationalExpr
  9360. // | EqualityExpr '!=' RelationalExpr
  9361. // RelationalExpr ::= AdditiveExpr
  9362. // | RelationalExpr '<' AdditiveExpr
  9363. // | RelationalExpr '>' AdditiveExpr
  9364. // | RelationalExpr '<=' AdditiveExpr
  9365. // | RelationalExpr '>=' AdditiveExpr
  9366. // AdditiveExpr ::= MultiplicativeExpr
  9367. // | AdditiveExpr '+' MultiplicativeExpr
  9368. // | AdditiveExpr '-' MultiplicativeExpr
  9369. // MultiplicativeExpr ::= UnaryExpr
  9370. // | MultiplicativeExpr '*' UnaryExpr
  9371. // | MultiplicativeExpr 'div' UnaryExpr
  9372. // | MultiplicativeExpr 'mod' UnaryExpr
  9373. xpath_ast_node* parse_expression(int limit = 0)
  9374. {
  9375. xpath_ast_node* n = parse_path_or_unary_expression();
  9376. if (!n) return 0;
  9377. return parse_expression_rec(n, limit);
  9378. }
  9379. 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)
  9380. {
  9381. }
  9382. xpath_ast_node* parse()
  9383. {
  9384. xpath_ast_node* n = parse_expression();
  9385. if (!n) return 0;
  9386. // check if there are unparsed tokens left
  9387. if (_lexer.current() != lex_eof)
  9388. return error("Incorrect query");
  9389. return n;
  9390. }
  9391. static xpath_ast_node* parse(const char_t* query, xpath_variable_set* variables, xpath_allocator* alloc, xpath_parse_result* result)
  9392. {
  9393. xpath_parser parser(query, variables, alloc, result);
  9394. return parser.parse();
  9395. }
  9396. };
  9397. struct xpath_query_impl
  9398. {
  9399. static xpath_query_impl* create()
  9400. {
  9401. void* memory = xml_memory::allocate(sizeof(xpath_query_impl));
  9402. if (!memory) return 0;
  9403. return new (memory) xpath_query_impl();
  9404. }
  9405. static void destroy(xpath_query_impl* impl)
  9406. {
  9407. // free all allocated pages
  9408. impl->alloc.release();
  9409. // free allocator memory (with the first page)
  9410. xml_memory::deallocate(impl);
  9411. }
  9412. xpath_query_impl(): root(0), alloc(&block, &oom), oom(false)
  9413. {
  9414. block.next = 0;
  9415. block.capacity = sizeof(block.data);
  9416. }
  9417. xpath_ast_node* root;
  9418. xpath_allocator alloc;
  9419. xpath_memory_block block;
  9420. bool oom;
  9421. };
  9422. PUGI__FN impl::xpath_ast_node* evaluate_node_set_prepare(xpath_query_impl* impl)
  9423. {
  9424. if (!impl) return 0;
  9425. if (impl->root->rettype() != xpath_type_node_set)
  9426. {
  9427. #ifdef PUGIXML_NO_EXCEPTIONS
  9428. return 0;
  9429. #else
  9430. xpath_parse_result res;
  9431. res.error = "Expression does not evaluate to node set";
  9432. throw xpath_exception(res);
  9433. #endif
  9434. }
  9435. return impl->root;
  9436. }
  9437. PUGI__NS_END
  9438. namespace pugi
  9439. {
  9440. #ifndef PUGIXML_NO_EXCEPTIONS
  9441. PUGI__FN xpath_exception::xpath_exception(const xpath_parse_result& result_): _result(result_)
  9442. {
  9443. assert(_result.error);
  9444. }
  9445. PUGI__FN const char* xpath_exception::what() const throw()
  9446. {
  9447. return _result.error;
  9448. }
  9449. PUGI__FN const xpath_parse_result& xpath_exception::result() const
  9450. {
  9451. return _result;
  9452. }
  9453. #endif
  9454. PUGI__FN xpath_node::xpath_node()
  9455. {
  9456. }
  9457. PUGI__FN xpath_node::xpath_node(const xml_node& node_): _node(node_)
  9458. {
  9459. }
  9460. PUGI__FN xpath_node::xpath_node(const xml_attribute& attribute_, const xml_node& parent_): _node(attribute_ ? parent_ : xml_node()), _attribute(attribute_)
  9461. {
  9462. }
  9463. PUGI__FN xml_node xpath_node::node() const
  9464. {
  9465. return _attribute ? xml_node() : _node;
  9466. }
  9467. PUGI__FN xml_attribute xpath_node::attribute() const
  9468. {
  9469. return _attribute;
  9470. }
  9471. PUGI__FN xml_node xpath_node::parent() const
  9472. {
  9473. return _attribute ? _node : _node.parent();
  9474. }
  9475. PUGI__FN static void unspecified_bool_xpath_node(xpath_node***)
  9476. {
  9477. }
  9478. PUGI__FN xpath_node::operator xpath_node::unspecified_bool_type() const
  9479. {
  9480. return (_node || _attribute) ? unspecified_bool_xpath_node : 0;
  9481. }
  9482. PUGI__FN bool xpath_node::operator!() const
  9483. {
  9484. return !(_node || _attribute);
  9485. }
  9486. PUGI__FN bool xpath_node::operator==(const xpath_node& n) const
  9487. {
  9488. return _node == n._node && _attribute == n._attribute;
  9489. }
  9490. PUGI__FN bool xpath_node::operator!=(const xpath_node& n) const
  9491. {
  9492. return _node != n._node || _attribute != n._attribute;
  9493. }
  9494. #ifdef __BORLANDC__
  9495. PUGI__FN bool operator&&(const xpath_node& lhs, bool rhs)
  9496. {
  9497. return (bool)lhs && rhs;
  9498. }
  9499. PUGI__FN bool operator||(const xpath_node& lhs, bool rhs)
  9500. {
  9501. return (bool)lhs || rhs;
  9502. }
  9503. #endif
  9504. PUGI__FN void xpath_node_set::_assign(const_iterator begin_, const_iterator end_, type_t type_)
  9505. {
  9506. assert(begin_ <= end_);
  9507. size_t size_ = static_cast<size_t>(end_ - begin_);
  9508. // use internal buffer for 0 or 1 elements, heap buffer otherwise
  9509. xpath_node* storage = (size_ <= 1) ? _storage : static_cast<xpath_node*>(impl::xml_memory::allocate(size_ * sizeof(xpath_node)));
  9510. if (!storage)
  9511. {
  9512. #ifdef PUGIXML_NO_EXCEPTIONS
  9513. return;
  9514. #else
  9515. throw std::bad_alloc();
  9516. #endif
  9517. }
  9518. // deallocate old buffer
  9519. if (_begin != _storage)
  9520. impl::xml_memory::deallocate(_begin);
  9521. // size check is necessary because for begin_ = end_ = nullptr, memcpy is UB
  9522. if (size_)
  9523. memcpy(storage, begin_, size_ * sizeof(xpath_node));
  9524. _begin = storage;
  9525. _end = storage + size_;
  9526. _type = type_;
  9527. }
  9528. #ifdef PUGIXML_HAS_MOVE
  9529. PUGI__FN void xpath_node_set::_move(xpath_node_set& rhs) PUGIXML_NOEXCEPT
  9530. {
  9531. _type = rhs._type;
  9532. _storage[0] = rhs._storage[0];
  9533. _begin = (rhs._begin == rhs._storage) ? _storage : rhs._begin;
  9534. _end = _begin + (rhs._end - rhs._begin);
  9535. rhs._type = type_unsorted;
  9536. rhs._begin = rhs._storage;
  9537. rhs._end = rhs._storage;
  9538. }
  9539. #endif
  9540. PUGI__FN xpath_node_set::xpath_node_set(): _type(type_unsorted), _begin(_storage), _end(_storage)
  9541. {
  9542. }
  9543. PUGI__FN xpath_node_set::xpath_node_set(const_iterator begin_, const_iterator end_, type_t type_): _type(type_unsorted), _begin(_storage), _end(_storage)
  9544. {
  9545. _assign(begin_, end_, type_);
  9546. }
  9547. PUGI__FN xpath_node_set::~xpath_node_set()
  9548. {
  9549. if (_begin != _storage)
  9550. impl::xml_memory::deallocate(_begin);
  9551. }
  9552. PUGI__FN xpath_node_set::xpath_node_set(const xpath_node_set& ns): _type(type_unsorted), _begin(_storage), _end(_storage)
  9553. {
  9554. _assign(ns._begin, ns._end, ns._type);
  9555. }
  9556. PUGI__FN xpath_node_set& xpath_node_set::operator=(const xpath_node_set& ns)
  9557. {
  9558. if (this == &ns) return *this;
  9559. _assign(ns._begin, ns._end, ns._type);
  9560. return *this;
  9561. }
  9562. #ifdef PUGIXML_HAS_MOVE
  9563. PUGI__FN xpath_node_set::xpath_node_set(xpath_node_set&& rhs) PUGIXML_NOEXCEPT: _type(type_unsorted), _begin(_storage), _end(_storage)
  9564. {
  9565. _move(rhs);
  9566. }
  9567. PUGI__FN xpath_node_set& xpath_node_set::operator=(xpath_node_set&& rhs) PUGIXML_NOEXCEPT
  9568. {
  9569. if (this == &rhs) return *this;
  9570. if (_begin != _storage)
  9571. impl::xml_memory::deallocate(_begin);
  9572. _move(rhs);
  9573. return *this;
  9574. }
  9575. #endif
  9576. PUGI__FN xpath_node_set::type_t xpath_node_set::type() const
  9577. {
  9578. return _type;
  9579. }
  9580. PUGI__FN size_t xpath_node_set::size() const
  9581. {
  9582. return _end - _begin;
  9583. }
  9584. PUGI__FN bool xpath_node_set::empty() const
  9585. {
  9586. return _begin == _end;
  9587. }
  9588. PUGI__FN const xpath_node& xpath_node_set::operator[](size_t index) const
  9589. {
  9590. assert(index < size());
  9591. return _begin[index];
  9592. }
  9593. PUGI__FN xpath_node_set::const_iterator xpath_node_set::begin() const
  9594. {
  9595. return _begin;
  9596. }
  9597. PUGI__FN xpath_node_set::const_iterator xpath_node_set::end() const
  9598. {
  9599. return _end;
  9600. }
  9601. PUGI__FN void xpath_node_set::sort(bool reverse)
  9602. {
  9603. _type = impl::xpath_sort(_begin, _end, _type, reverse);
  9604. }
  9605. PUGI__FN xpath_node xpath_node_set::first() const
  9606. {
  9607. return impl::xpath_first(_begin, _end, _type);
  9608. }
  9609. PUGI__FN xpath_parse_result::xpath_parse_result(): error("Internal error"), offset(0)
  9610. {
  9611. }
  9612. PUGI__FN xpath_parse_result::operator bool() const
  9613. {
  9614. return error == 0;
  9615. }
  9616. PUGI__FN const char* xpath_parse_result::description() const
  9617. {
  9618. return error ? error : "No error";
  9619. }
  9620. PUGI__FN xpath_variable::xpath_variable(xpath_value_type type_): _type(type_), _next(0)
  9621. {
  9622. }
  9623. PUGI__FN const char_t* xpath_variable::name() const
  9624. {
  9625. switch (_type)
  9626. {
  9627. case xpath_type_node_set:
  9628. return static_cast<const impl::xpath_variable_node_set*>(this)->name;
  9629. case xpath_type_number:
  9630. return static_cast<const impl::xpath_variable_number*>(this)->name;
  9631. case xpath_type_string:
  9632. return static_cast<const impl::xpath_variable_string*>(this)->name;
  9633. case xpath_type_boolean:
  9634. return static_cast<const impl::xpath_variable_boolean*>(this)->name;
  9635. default:
  9636. assert(false && "Invalid variable type"); // unreachable
  9637. return 0;
  9638. }
  9639. }
  9640. PUGI__FN xpath_value_type xpath_variable::type() const
  9641. {
  9642. return _type;
  9643. }
  9644. PUGI__FN bool xpath_variable::get_boolean() const
  9645. {
  9646. return (_type == xpath_type_boolean) ? static_cast<const impl::xpath_variable_boolean*>(this)->value : false;
  9647. }
  9648. PUGI__FN double xpath_variable::get_number() const
  9649. {
  9650. return (_type == xpath_type_number) ? static_cast<const impl::xpath_variable_number*>(this)->value : impl::gen_nan();
  9651. }
  9652. PUGI__FN const char_t* xpath_variable::get_string() const
  9653. {
  9654. const char_t* value = (_type == xpath_type_string) ? static_cast<const impl::xpath_variable_string*>(this)->value : 0;
  9655. return value ? value : PUGIXML_TEXT("");
  9656. }
  9657. PUGI__FN const xpath_node_set& xpath_variable::get_node_set() const
  9658. {
  9659. return (_type == xpath_type_node_set) ? static_cast<const impl::xpath_variable_node_set*>(this)->value : impl::dummy_node_set;
  9660. }
  9661. PUGI__FN bool xpath_variable::set(bool value)
  9662. {
  9663. if (_type != xpath_type_boolean) return false;
  9664. static_cast<impl::xpath_variable_boolean*>(this)->value = value;
  9665. return true;
  9666. }
  9667. PUGI__FN bool xpath_variable::set(double value)
  9668. {
  9669. if (_type != xpath_type_number) return false;
  9670. static_cast<impl::xpath_variable_number*>(this)->value = value;
  9671. return true;
  9672. }
  9673. PUGI__FN bool xpath_variable::set(const char_t* value)
  9674. {
  9675. if (_type != xpath_type_string) return false;
  9676. impl::xpath_variable_string* var = static_cast<impl::xpath_variable_string*>(this);
  9677. // duplicate string
  9678. size_t size = (impl::strlength(value) + 1) * sizeof(char_t);
  9679. char_t* copy = static_cast<char_t*>(impl::xml_memory::allocate(size));
  9680. if (!copy) return false;
  9681. memcpy(copy, value, size);
  9682. // replace old string
  9683. if (var->value) impl::xml_memory::deallocate(var->value);
  9684. var->value = copy;
  9685. return true;
  9686. }
  9687. PUGI__FN bool xpath_variable::set(const xpath_node_set& value)
  9688. {
  9689. if (_type != xpath_type_node_set) return false;
  9690. static_cast<impl::xpath_variable_node_set*>(this)->value = value;
  9691. return true;
  9692. }
  9693. PUGI__FN xpath_variable_set::xpath_variable_set()
  9694. {
  9695. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9696. _data[i] = 0;
  9697. }
  9698. PUGI__FN xpath_variable_set::~xpath_variable_set()
  9699. {
  9700. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9701. _destroy(_data[i]);
  9702. }
  9703. PUGI__FN xpath_variable_set::xpath_variable_set(const xpath_variable_set& rhs)
  9704. {
  9705. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9706. _data[i] = 0;
  9707. _assign(rhs);
  9708. }
  9709. PUGI__FN xpath_variable_set& xpath_variable_set::operator=(const xpath_variable_set& rhs)
  9710. {
  9711. if (this == &rhs) return *this;
  9712. _assign(rhs);
  9713. return *this;
  9714. }
  9715. #ifdef PUGIXML_HAS_MOVE
  9716. PUGI__FN xpath_variable_set::xpath_variable_set(xpath_variable_set&& rhs) PUGIXML_NOEXCEPT
  9717. {
  9718. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9719. {
  9720. _data[i] = rhs._data[i];
  9721. rhs._data[i] = 0;
  9722. }
  9723. }
  9724. PUGI__FN xpath_variable_set& xpath_variable_set::operator=(xpath_variable_set&& rhs) PUGIXML_NOEXCEPT
  9725. {
  9726. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9727. {
  9728. _destroy(_data[i]);
  9729. _data[i] = rhs._data[i];
  9730. rhs._data[i] = 0;
  9731. }
  9732. return *this;
  9733. }
  9734. #endif
  9735. PUGI__FN void xpath_variable_set::_assign(const xpath_variable_set& rhs)
  9736. {
  9737. xpath_variable_set temp;
  9738. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9739. if (rhs._data[i] && !_clone(rhs._data[i], &temp._data[i]))
  9740. return;
  9741. _swap(temp);
  9742. }
  9743. PUGI__FN void xpath_variable_set::_swap(xpath_variable_set& rhs)
  9744. {
  9745. for (size_t i = 0; i < sizeof(_data) / sizeof(_data[0]); ++i)
  9746. {
  9747. xpath_variable* chain = _data[i];
  9748. _data[i] = rhs._data[i];
  9749. rhs._data[i] = chain;
  9750. }
  9751. }
  9752. PUGI__FN xpath_variable* xpath_variable_set::_find(const char_t* name) const
  9753. {
  9754. const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
  9755. size_t hash = impl::hash_string(name) % hash_size;
  9756. // look for existing variable
  9757. for (xpath_variable* var = _data[hash]; var; var = var->_next)
  9758. if (impl::strequal(var->name(), name))
  9759. return var;
  9760. return 0;
  9761. }
  9762. PUGI__FN bool xpath_variable_set::_clone(xpath_variable* var, xpath_variable** out_result)
  9763. {
  9764. xpath_variable* last = 0;
  9765. while (var)
  9766. {
  9767. // allocate storage for new variable
  9768. xpath_variable* nvar = impl::new_xpath_variable(var->_type, var->name());
  9769. if (!nvar) return false;
  9770. // link the variable to the result immediately to handle failures gracefully
  9771. if (last)
  9772. last->_next = nvar;
  9773. else
  9774. *out_result = nvar;
  9775. last = nvar;
  9776. // copy the value; this can fail due to out-of-memory conditions
  9777. if (!impl::copy_xpath_variable(nvar, var)) return false;
  9778. var = var->_next;
  9779. }
  9780. return true;
  9781. }
  9782. PUGI__FN void xpath_variable_set::_destroy(xpath_variable* var)
  9783. {
  9784. while (var)
  9785. {
  9786. xpath_variable* next = var->_next;
  9787. impl::delete_xpath_variable(var->_type, var);
  9788. var = next;
  9789. }
  9790. }
  9791. PUGI__FN xpath_variable* xpath_variable_set::add(const char_t* name, xpath_value_type type)
  9792. {
  9793. const size_t hash_size = sizeof(_data) / sizeof(_data[0]);
  9794. size_t hash = impl::hash_string(name) % hash_size;
  9795. // look for existing variable
  9796. for (xpath_variable* var = _data[hash]; var; var = var->_next)
  9797. if (impl::strequal(var->name(), name))
  9798. return var->type() == type ? var : 0;
  9799. // add new variable
  9800. xpath_variable* result = impl::new_xpath_variable(type, name);
  9801. if (result)
  9802. {
  9803. result->_next = _data[hash];
  9804. _data[hash] = result;
  9805. }
  9806. return result;
  9807. }
  9808. PUGI__FN bool xpath_variable_set::set(const char_t* name, bool value)
  9809. {
  9810. xpath_variable* var = add(name, xpath_type_boolean);
  9811. return var ? var->set(value) : false;
  9812. }
  9813. PUGI__FN bool xpath_variable_set::set(const char_t* name, double value)
  9814. {
  9815. xpath_variable* var = add(name, xpath_type_number);
  9816. return var ? var->set(value) : false;
  9817. }
  9818. PUGI__FN bool xpath_variable_set::set(const char_t* name, const char_t* value)
  9819. {
  9820. xpath_variable* var = add(name, xpath_type_string);
  9821. return var ? var->set(value) : false;
  9822. }
  9823. PUGI__FN bool xpath_variable_set::set(const char_t* name, const xpath_node_set& value)
  9824. {
  9825. xpath_variable* var = add(name, xpath_type_node_set);
  9826. return var ? var->set(value) : false;
  9827. }
  9828. PUGI__FN xpath_variable* xpath_variable_set::get(const char_t* name)
  9829. {
  9830. return _find(name);
  9831. }
  9832. PUGI__FN const xpath_variable* xpath_variable_set::get(const char_t* name) const
  9833. {
  9834. return _find(name);
  9835. }
  9836. PUGI__FN xpath_query::xpath_query(const char_t* query, xpath_variable_set* variables): _impl(0)
  9837. {
  9838. impl::xpath_query_impl* qimpl = impl::xpath_query_impl::create();
  9839. if (!qimpl)
  9840. {
  9841. #ifdef PUGIXML_NO_EXCEPTIONS
  9842. _result.error = "Out of memory";
  9843. #else
  9844. throw std::bad_alloc();
  9845. #endif
  9846. }
  9847. else
  9848. {
  9849. using impl::auto_deleter; // MSVC7 workaround
  9850. auto_deleter<impl::xpath_query_impl> impl(qimpl, impl::xpath_query_impl::destroy);
  9851. qimpl->root = impl::xpath_parser::parse(query, variables, &qimpl->alloc, &_result);
  9852. if (qimpl->root)
  9853. {
  9854. qimpl->root->optimize(&qimpl->alloc);
  9855. _impl = impl.release();
  9856. _result.error = 0;
  9857. }
  9858. else
  9859. {
  9860. #ifdef PUGIXML_NO_EXCEPTIONS
  9861. if (qimpl->oom) _result.error = "Out of memory";
  9862. #else
  9863. if (qimpl->oom) throw std::bad_alloc();
  9864. throw xpath_exception(_result);
  9865. #endif
  9866. }
  9867. }
  9868. }
  9869. PUGI__FN xpath_query::xpath_query(): _impl(0)
  9870. {
  9871. }
  9872. PUGI__FN xpath_query::~xpath_query()
  9873. {
  9874. if (_impl)
  9875. impl::xpath_query_impl::destroy(static_cast<impl::xpath_query_impl*>(_impl));
  9876. }
  9877. #ifdef PUGIXML_HAS_MOVE
  9878. PUGI__FN xpath_query::xpath_query(xpath_query&& rhs) PUGIXML_NOEXCEPT
  9879. {
  9880. _impl = rhs._impl;
  9881. _result = rhs._result;
  9882. rhs._impl = 0;
  9883. rhs._result = xpath_parse_result();
  9884. }
  9885. PUGI__FN xpath_query& xpath_query::operator=(xpath_query&& rhs) PUGIXML_NOEXCEPT
  9886. {
  9887. if (this == &rhs) return *this;
  9888. if (_impl)
  9889. impl::xpath_query_impl::destroy(static_cast<impl::xpath_query_impl*>(_impl));
  9890. _impl = rhs._impl;
  9891. _result = rhs._result;
  9892. rhs._impl = 0;
  9893. rhs._result = xpath_parse_result();
  9894. return *this;
  9895. }
  9896. #endif
  9897. PUGI__FN xpath_value_type xpath_query::return_type() const
  9898. {
  9899. if (!_impl) return xpath_type_none;
  9900. return static_cast<impl::xpath_query_impl*>(_impl)->root->rettype();
  9901. }
  9902. PUGI__FN bool xpath_query::evaluate_boolean(const xpath_node& n) const
  9903. {
  9904. if (!_impl) return false;
  9905. impl::xpath_context c(n, 1, 1);
  9906. impl::xpath_stack_data sd;
  9907. bool r = static_cast<impl::xpath_query_impl*>(_impl)->root->eval_boolean(c, sd.stack);
  9908. if (sd.oom)
  9909. {
  9910. #ifdef PUGIXML_NO_EXCEPTIONS
  9911. return false;
  9912. #else
  9913. throw std::bad_alloc();
  9914. #endif
  9915. }
  9916. return r;
  9917. }
  9918. PUGI__FN double xpath_query::evaluate_number(const xpath_node& n) const
  9919. {
  9920. if (!_impl) return impl::gen_nan();
  9921. impl::xpath_context c(n, 1, 1);
  9922. impl::xpath_stack_data sd;
  9923. double r = static_cast<impl::xpath_query_impl*>(_impl)->root->eval_number(c, sd.stack);
  9924. if (sd.oom)
  9925. {
  9926. #ifdef PUGIXML_NO_EXCEPTIONS
  9927. return impl::gen_nan();
  9928. #else
  9929. throw std::bad_alloc();
  9930. #endif
  9931. }
  9932. return r;
  9933. }
  9934. #ifndef PUGIXML_NO_STL
  9935. PUGI__FN string_t xpath_query::evaluate_string(const xpath_node& n) const
  9936. {
  9937. if (!_impl) return string_t();
  9938. impl::xpath_context c(n, 1, 1);
  9939. impl::xpath_stack_data sd;
  9940. impl::xpath_string r = static_cast<impl::xpath_query_impl*>(_impl)->root->eval_string(c, sd.stack);
  9941. if (sd.oom)
  9942. {
  9943. #ifdef PUGIXML_NO_EXCEPTIONS
  9944. return string_t();
  9945. #else
  9946. throw std::bad_alloc();
  9947. #endif
  9948. }
  9949. return string_t(r.c_str(), r.length());
  9950. }
  9951. #endif
  9952. PUGI__FN size_t xpath_query::evaluate_string(char_t* buffer, size_t capacity, const xpath_node& n) const
  9953. {
  9954. impl::xpath_context c(n, 1, 1);
  9955. impl::xpath_stack_data sd;
  9956. impl::xpath_string r = _impl ? static_cast<impl::xpath_query_impl*>(_impl)->root->eval_string(c, sd.stack) : impl::xpath_string();
  9957. if (sd.oom)
  9958. {
  9959. #ifdef PUGIXML_NO_EXCEPTIONS
  9960. r = impl::xpath_string();
  9961. #else
  9962. throw std::bad_alloc();
  9963. #endif
  9964. }
  9965. size_t full_size = r.length() + 1;
  9966. if (capacity > 0)
  9967. {
  9968. size_t size = (full_size < capacity) ? full_size : capacity;
  9969. assert(size > 0);
  9970. memcpy(buffer, r.c_str(), (size - 1) * sizeof(char_t));
  9971. buffer[size - 1] = 0;
  9972. }
  9973. return full_size;
  9974. }
  9975. PUGI__FN xpath_node_set xpath_query::evaluate_node_set(const xpath_node& n) const
  9976. {
  9977. impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl));
  9978. if (!root) return xpath_node_set();
  9979. impl::xpath_context c(n, 1, 1);
  9980. impl::xpath_stack_data sd;
  9981. impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_all);
  9982. if (sd.oom)
  9983. {
  9984. #ifdef PUGIXML_NO_EXCEPTIONS
  9985. return xpath_node_set();
  9986. #else
  9987. throw std::bad_alloc();
  9988. #endif
  9989. }
  9990. return xpath_node_set(r.begin(), r.end(), r.type());
  9991. }
  9992. PUGI__FN xpath_node xpath_query::evaluate_node(const xpath_node& n) const
  9993. {
  9994. impl::xpath_ast_node* root = impl::evaluate_node_set_prepare(static_cast<impl::xpath_query_impl*>(_impl));
  9995. if (!root) return xpath_node();
  9996. impl::xpath_context c(n, 1, 1);
  9997. impl::xpath_stack_data sd;
  9998. impl::xpath_node_set_raw r = root->eval_node_set(c, sd.stack, impl::nodeset_eval_first);
  9999. if (sd.oom)
  10000. {
  10001. #ifdef PUGIXML_NO_EXCEPTIONS
  10002. return xpath_node();
  10003. #else
  10004. throw std::bad_alloc();
  10005. #endif
  10006. }
  10007. return r.first();
  10008. }
  10009. PUGI__FN const xpath_parse_result& xpath_query::result() const
  10010. {
  10011. return _result;
  10012. }
  10013. PUGI__FN static void unspecified_bool_xpath_query(xpath_query***)
  10014. {
  10015. }
  10016. PUGI__FN xpath_query::operator xpath_query::unspecified_bool_type() const
  10017. {
  10018. return _impl ? unspecified_bool_xpath_query : 0;
  10019. }
  10020. PUGI__FN bool xpath_query::operator!() const
  10021. {
  10022. return !_impl;
  10023. }
  10024. PUGI__FN xpath_node xml_node::select_node(const char_t* query, xpath_variable_set* variables) const
  10025. {
  10026. xpath_query q(query, variables);
  10027. return q.evaluate_node(*this);
  10028. }
  10029. PUGI__FN xpath_node xml_node::select_node(const xpath_query& query) const
  10030. {
  10031. return query.evaluate_node(*this);
  10032. }
  10033. PUGI__FN xpath_node_set xml_node::select_nodes(const char_t* query, xpath_variable_set* variables) const
  10034. {
  10035. xpath_query q(query, variables);
  10036. return q.evaluate_node_set(*this);
  10037. }
  10038. PUGI__FN xpath_node_set xml_node::select_nodes(const xpath_query& query) const
  10039. {
  10040. return query.evaluate_node_set(*this);
  10041. }
  10042. PUGI__FN xpath_node xml_node::select_single_node(const char_t* query, xpath_variable_set* variables) const
  10043. {
  10044. xpath_query q(query, variables);
  10045. return q.evaluate_node(*this);
  10046. }
  10047. PUGI__FN xpath_node xml_node::select_single_node(const xpath_query& query) const
  10048. {
  10049. return query.evaluate_node(*this);
  10050. }
  10051. }
  10052. #endif
  10053. #ifdef __BORLANDC__
  10054. # pragma option pop
  10055. #endif
  10056. // Intel C++ does not properly keep warning state for function templates,
  10057. // so popping warning state at the end of translation unit leads to warnings in the middle.
  10058. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  10059. # pragma warning(pop)
  10060. #endif
  10061. #if defined(_MSC_VER) && defined(__c2__)
  10062. # pragma clang diagnostic pop
  10063. #endif
  10064. // Undefine all local macros (makes sure we're not leaking macros in header-only mode)
  10065. #undef PUGI__NO_INLINE
  10066. #undef PUGI__UNLIKELY
  10067. #undef PUGI__STATIC_ASSERT
  10068. #undef PUGI__DMC_VOLATILE
  10069. #undef PUGI__UNSIGNED_OVERFLOW
  10070. #undef PUGI__MSVC_CRT_VERSION
  10071. #undef PUGI__SNPRINTF
  10072. #undef PUGI__NS_BEGIN
  10073. #undef PUGI__NS_END
  10074. #undef PUGI__FN
  10075. #undef PUGI__FN_NO_INLINE
  10076. #undef PUGI__GETHEADER_IMPL
  10077. #undef PUGI__GETPAGE_IMPL
  10078. #undef PUGI__GETPAGE
  10079. #undef PUGI__NODETYPE
  10080. #undef PUGI__IS_CHARTYPE_IMPL
  10081. #undef PUGI__IS_CHARTYPE
  10082. #undef PUGI__IS_CHARTYPEX
  10083. #undef PUGI__ENDSWITH
  10084. #undef PUGI__SKIPWS
  10085. #undef PUGI__OPTSET
  10086. #undef PUGI__PUSHNODE
  10087. #undef PUGI__POPNODE
  10088. #undef PUGI__SCANFOR
  10089. #undef PUGI__SCANWHILE
  10090. #undef PUGI__SCANWHILE_UNROLL
  10091. #undef PUGI__ENDSEG
  10092. #undef PUGI__THROW_ERROR
  10093. #undef PUGI__CHECK_ERROR
  10094. #endif
  10095. /**
  10096. * Copyright (c) 2006-2019 Arseny Kapoulkine
  10097. *
  10098. * Permission is hereby granted, free of charge, to any person
  10099. * obtaining a copy of this software and associated documentation
  10100. * files (the "Software"), to deal in the Software without
  10101. * restriction, including without limitation the rights to use,
  10102. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  10103. * copies of the Software, and to permit persons to whom the
  10104. * Software is furnished to do so, subject to the following
  10105. * conditions:
  10106. *
  10107. * The above copyright notice and this permission notice shall be
  10108. * included in all copies or substantial portions of the Software.
  10109. *
  10110. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  10111. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  10112. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  10113. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  10114. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  10115. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  10116. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  10117. * OTHER DEALINGS IN THE SOFTWARE.
  10118. */