syn_parse.rs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411
  1. //! Implementation of `syn::parse::Parse` for styles, and associated helper data/functions.
  2. // TODO make all parsers use HyphenWord where appropriate.
  3. // TODO make all error messages nice
  4. // TODO 100% test coverage
  5. // TODO see if I can get https://github.com/rust-lang/rust/issues/67544 accepted. then change "em" to
  6. // em and "ex" to ex.
  7. // TODO Split out extra "Dynamic" layer for each type for use in proc macro (so we can have `{ <arbitary
  8. // rust code> }`)
  9. use crate::*;
  10. use proc_macro2::Span;
  11. use std::{
  12. cell::RefCell,
  13. collections::BTreeSet,
  14. fmt::{self, Write},
  15. ops::RangeBounds,
  16. str,
  17. };
  18. use syn::{
  19. ext::IdentExt,
  20. parse::{discouraged::Speculative, Parse, ParseStream},
  21. punctuated::Punctuated,
  22. spanned::Spanned,
  23. Ident, Token,
  24. };
  25. use super::{DynamicStyle, DynamicStyles, Styles};
  26. impl Parse for DynamicStyles {
  27. fn parse(s: ParseStream) -> syn::Result<Self> {
  28. let punc = s.parse_terminated::<_, Token![;]>(<DynamicStyle as Parse>::parse)?;
  29. Ok(DynamicStyles::from(punc.into_iter().collect::<Vec<_>>()))
  30. }
  31. }
  32. impl Parse for Styles {
  33. fn parse(s: ParseStream) -> syn::Result<Self> {
  34. let punc = s.parse_terminated::<_, Token![;]>(<Style as Parse>::parse)?;
  35. Ok(Styles::from(punc.into_iter().collect::<Vec<_>>()))
  36. }
  37. }
  38. impl Parse for DynamicStyle {
  39. fn parse(s: ParseStream) -> syn::Result<Self> {
  40. // Pass through brackets
  41. if s.peek(syn::token::Brace) {
  42. Ok(DynamicStyle::Dynamic(s.parse()?))
  43. } else {
  44. Ok(DynamicStyle::Literal(s.parse()?))
  45. }
  46. }
  47. }
  48. impl Parse for Style {
  49. fn parse(s: ParseStream) -> syn::Result<Self> {
  50. if s.peek(syn::LitStr) {
  51. let unchecked: syn::LitStr = s.parse()?;
  52. return Ok(Style::Unchecked(unchecked.value()));
  53. }
  54. let name: HyphenWord = s.parse()?;
  55. if name.try_match("dummy") {
  56. return Ok(Style::Dummy);
  57. }
  58. s.parse::<Token![:]>()?;
  59. let output = if name.try_match("align-content") {
  60. Style::AlignContent(s.parse()?)
  61. } else if name.try_match("align-items") {
  62. Style::AlignItems(s.parse()?)
  63. } else if name.try_match("align-self") {
  64. Style::AlignSelf(s.parse()?)
  65. // all
  66. // background
  67. } else if name.try_match("background-attachment") {
  68. Style::BackgroundAttachment(s.parse()?)
  69. } else if name.try_match("background-blend-mode") {
  70. Style::BackgroundBlendMode(s.parse()?)
  71. } else if name.try_match("background-clip") {
  72. Style::BackgroundClip(s.parse()?)
  73. } else if name.try_match("background-color") {
  74. Style::BackgroundColor(s.parse()?)
  75. } else if name.try_match("background-image") {
  76. Style::BackgroundImage(s.parse()?)
  77. } else if name.try_match("background-origin") {
  78. Style::BackgroundOrigin(s.parse()?)
  79. } else if name.try_match("background-position") {
  80. Style::BackgroundPosition(s.parse()?)
  81. } else if name.try_match("background-repeat") {
  82. Style::BackgroundRepeat(s.parse()?)
  83. } else if name.try_match("background-size") {
  84. Style::BackgroundSize(s.parse()?)
  85. } else if name.try_match("border") {
  86. Style::Border(s.parse()?)
  87. } else if name.try_match("border-bottom") {
  88. Style::BorderBottom(s.parse()?)
  89. } else if name.try_match("border-bottom-color") {
  90. Style::BorderBottomColor(s.parse()?)
  91. } else if name.try_match("border-bottom-left-radius") {
  92. Style::BorderBottomLeftRadius(s.parse()?)
  93. } else if name.try_match("border-bottom-right-radius") {
  94. Style::BorderBottomRightRadius(s.parse()?)
  95. } else if name.try_match("border-bottom-style") {
  96. Style::BorderBottomStyle(s.parse()?)
  97. } else if name.try_match("border-bottom-width") {
  98. Style::BorderBottomWidth(s.parse()?)
  99. } else if name.try_match("border-collapse") {
  100. Style::BorderCollapse(s.parse()?)
  101. } else if name.try_match("border-color") {
  102. Style::BorderColor(s.parse()?)
  103. // border-image
  104. // border-image-outset
  105. // border-image-repeat
  106. // border-image-slice
  107. // border-image-source
  108. // border-image-width
  109. } else if name.try_match("border-left") {
  110. Style::BorderLeft(s.parse()?)
  111. } else if name.try_match("border-left-color") {
  112. Style::BorderLeftColor(s.parse()?)
  113. } else if name.try_match("border-left-style") {
  114. Style::BorderLeftStyle(s.parse()?)
  115. } else if name.try_match("border-left-width") {
  116. Style::BorderLeftWidth(s.parse()?)
  117. } else if name.try_match("border-radius") {
  118. Style::BorderRadius(s.parse()?)
  119. } else if name.try_match("border-right") {
  120. Style::BorderRight(s.parse()?)
  121. } else if name.try_match("border-right-color") {
  122. Style::BorderRightColor(s.parse()?)
  123. } else if name.try_match("border-right-style") {
  124. Style::BorderRightStyle(s.parse()?)
  125. } else if name.try_match("border-right-width") {
  126. Style::BorderRightWidth(s.parse()?)
  127. // border-spacing
  128. } else if name.try_match("border-style") {
  129. Style::BorderStyle(s.parse()?)
  130. } else if name.try_match("border-top") {
  131. Style::BorderTop(s.parse()?)
  132. } else if name.try_match("border-top-color") {
  133. Style::BorderTopColor(s.parse()?)
  134. } else if name.try_match("border-top-left-radius") {
  135. Style::BorderTopLeftRadius(s.parse()?)
  136. } else if name.try_match("border-top-right-radius") {
  137. Style::BorderTopRightRadius(s.parse()?)
  138. } else if name.try_match("border-top-style") {
  139. Style::BorderTopStyle(s.parse()?)
  140. } else if name.try_match("border-top-width") {
  141. Style::BorderTopWidth(s.parse()?)
  142. } else if name.try_match("border-width") {
  143. Style::BorderWidth(s.parse()?)
  144. } else if name.try_match("bottom") {
  145. Style::Bottom(s.parse()?)
  146. // box-decoration-break
  147. } else if name.try_match("box-shadow") {
  148. Style::BoxShadow(s.parse()?)
  149. } else if name.try_match("box-sizing") {
  150. Style::BoxSizing(s.parse()?)
  151. // break-after
  152. // break-before
  153. // break-inside
  154. // caption-side
  155. // caret-color
  156. } else if name.try_match("clear") {
  157. Style::Clear(s.parse()?)
  158. // clip
  159. // clip-path
  160. // clip-rule
  161. } else if name.try_match("column-count") {
  162. Style::ColumnCount(s.parse()?)
  163. } else if name.try_match("color") {
  164. Style::Color(s.parse()?)
  165. // contain
  166. // content
  167. // counter-increment
  168. // counter-reset
  169. // cue
  170. // cue-after
  171. // cue-before
  172. } else if name.try_match("cursor") {
  173. Style::Cursor(s.parse()?)
  174. // direction
  175. } else if name.try_match("display") {
  176. Style::Display(s.parse()?)
  177. // elevation
  178. // empty-cells
  179. // flex
  180. } else if name.try_match("flex-basis") {
  181. Style::FlexBasis(s.parse()?)
  182. } else if name.try_match("flex-direction") {
  183. Style::FlexDirection(s.parse()?)
  184. // flex-flow
  185. } else if name.try_match("flex-grow") {
  186. let number: Number = s.parse()?;
  187. if !number.suffix.is_empty() {
  188. return Err(syn::Error::new(number.span, "expected number"));
  189. }
  190. Style::FlexGrow(number.value)
  191. } else if name.try_match("flex-shrink") {
  192. let number: Number = s.parse()?;
  193. if !number.suffix.is_empty() {
  194. return Err(syn::Error::new(number.span, "expected number"));
  195. }
  196. Style::FlexShrink(number.value)
  197. } else if name.try_match("flex-wrap") {
  198. Style::FlexWrap(s.parse()?)
  199. } else if name.try_match("float") {
  200. Style::Float(s.parse()?)
  201. // font
  202. } else if name.try_match("font-family") {
  203. Style::FontFamily(s.parse()?)
  204. // font-feature-settings
  205. // font-kerning
  206. } else if name.try_match("font-size") {
  207. Style::FontSize(s.parse()?)
  208. // font-size-adjust
  209. // font-stretch
  210. } else if name.try_match("font-style") {
  211. Style::FontStyle(s.parse()?)
  212. // font-synthesis
  213. // font-variant
  214. // font-variant-caps
  215. // font-variant-east-asian
  216. // font-variant-ligatures
  217. // font-variant-numeric
  218. // font-variant-position
  219. } else if name.try_match("font-weight") {
  220. Style::FontWeight(s.parse()?)
  221. // glyph-orientation-vertical
  222. // grid
  223. // grid-area
  224. // grid-auto-columns
  225. // grid-auto-flow
  226. // grid-auto-rows
  227. // grid-column
  228. // grid-column-end
  229. // grid-column-start
  230. // grid-row
  231. // grid-row-end
  232. // grid-row-start
  233. // grid-template
  234. // grid-template-areas
  235. // grid-template-columns
  236. // grid-template-rows
  237. } else if name.try_match("height") {
  238. Style::Height(s.parse()?)
  239. // image-orientation
  240. // image-rendering
  241. // isolation
  242. } else if name.try_match("justify-content") {
  243. Style::JustifyContent(s.parse()?)
  244. } else if name.try_match("left") {
  245. Style::Left(s.parse()?)
  246. // letter-spacing
  247. } else if name.try_match("line-height") {
  248. Style::LineHeight(s.parse()?)
  249. // list-style
  250. // list-style-image
  251. // list-style-position
  252. } else if name.try_match("list-style-type") {
  253. Style::ListStyleType(s.parse()?)
  254. } else if name.try_match("margin") {
  255. Style::Margin(s.parse()?)
  256. } else if name.try_match("margin-bottom") {
  257. Style::MarginBottom(s.parse()?)
  258. } else if name.try_match("margin-left") {
  259. Style::MarginLeft(s.parse()?)
  260. } else if name.try_match("margin-right") {
  261. Style::MarginRight(s.parse()?)
  262. } else if name.try_match("margin-top") {
  263. Style::MarginTop(s.parse()?)
  264. // mask
  265. // mask-border
  266. // mask-border-mode
  267. // mask-border-outset
  268. // mask-border-repeat
  269. // mask-border-slice
  270. // mask-border-source
  271. // mask-border-width
  272. // mask-clip
  273. // mask-composite
  274. // mask-image
  275. // mask-mode
  276. // mask-origin
  277. // mask-position
  278. // mask-repeat
  279. // mask-size
  280. // mask-type
  281. } else if name.try_match("max-height") {
  282. Style::MaxHeight(s.parse()?)
  283. } else if name.try_match("max-width") {
  284. Style::MaxWidth(s.parse()?)
  285. } else if name.try_match("min-height") {
  286. Style::MinHeight(s.parse()?)
  287. } else if name.try_match("min-width") {
  288. Style::MinWidth(s.parse()?)
  289. // mix-blend-mode
  290. } else if name.try_match("object-fit") {
  291. Style::ObjectFit(s.parse()?)
  292. // object-position
  293. // opacity
  294. // order
  295. // orphans
  296. // outline
  297. // outline-color
  298. // outline-offset
  299. // outline-style
  300. // outline-width
  301. } else if name.try_match("overflow") {
  302. Style::Overflow(s.parse()?)
  303. } else if name.try_match("overflow-x") {
  304. Style::OverflowX(s.parse()?)
  305. } else if name.try_match("overflow-y") {
  306. Style::OverflowY(s.parse()?)
  307. } else if name.try_match("padding") {
  308. Style::Padding(s.parse()?)
  309. } else if name.try_match("padding-bottom") {
  310. Style::PaddingBottom(s.parse()?)
  311. } else if name.try_match("padding-left") {
  312. Style::PaddingLeft(s.parse()?)
  313. } else if name.try_match("padding-right") {
  314. Style::PaddingRight(s.parse()?)
  315. } else if name.try_match("padding-top") {
  316. Style::PaddingTop(s.parse()?)
  317. // page-break-after
  318. // page-break-before
  319. // page-break-inside
  320. // pause
  321. // pause-after
  322. // pause-before
  323. // pitch
  324. // pitch-range
  325. // play-during
  326. } else if name.try_match("position") {
  327. Style::Position(s.parse()?)
  328. // quotes
  329. } else if name.try_match("resize") {
  330. Style::Resize(s.parse()?)
  331. // richness
  332. } else if name.try_match("right") {
  333. Style::Right(s.parse()?)
  334. // scroll-margin
  335. // scroll-margin-block
  336. // scroll-margin-block-end
  337. // scroll-margin-block-start
  338. // scroll-margin-bottom
  339. // scroll-margin-inline
  340. // scroll-margin-inline-end
  341. // scroll-margin-inline-start
  342. // scroll-margin-left
  343. // scroll-margin-right
  344. // scroll-margin-top
  345. // scroll-padding
  346. // scroll-padding-block
  347. // scroll-padding-block-end
  348. // scroll-padding-block-start
  349. // scroll-padding-bottom
  350. // scroll-padding-inline
  351. // scroll-padding-inline-end
  352. // scroll-padding-inline-start
  353. // scroll-padding-left
  354. // scroll-padding-right
  355. // scroll-padding-top
  356. // scroll-snap-align
  357. // scroll-snap-stop
  358. // scroll-snap-type
  359. // shape-image-threshold
  360. // shape-margin
  361. // shape-outside
  362. // speak
  363. // speak-header
  364. // speak-numeral
  365. // speak-punctuation
  366. // speech-rate
  367. // stress
  368. // table-layout
  369. } else if name.try_match("text-align") {
  370. Style::TextAlign(s.parse()?)
  371. // text-combine-upright
  372. // text-decoration
  373. // text-decoration-color
  374. // text-decoration-line
  375. // text-decoration-style
  376. // text-emphasis
  377. // text-emphasis-color
  378. // text-emphasis-position
  379. // text-emphasis-style
  380. // text-indent
  381. // text-orientation
  382. // text-overflow
  383. // text-shadow
  384. // text-transform
  385. // text-underline-position
  386. } else if name.try_match("top") {
  387. Style::Top(s.parse()?)
  388. // transform
  389. // transform-box
  390. // transform-origin
  391. // unicode-bidi
  392. // vertical-align
  393. // visibility
  394. // voice-family
  395. // volume
  396. } else if name.try_match("white-space") {
  397. Style::WhiteSpace(s.parse()?)
  398. } else if name.try_match("widows") {
  399. Style::Widows(integer(s, 1..)?)
  400. } else if name.try_match("width") {
  401. Style::Width(s.parse()?)
  402. // will-change
  403. // word-spacing
  404. // writing-mode
  405. // z-index
  406. } else {
  407. return Err(name.error());
  408. };
  409. if !finished_rule(s) {
  410. return Err(s.error("unexpected trailing tokens in style rule"));
  411. }
  412. Ok(output)
  413. }
  414. }
  415. impl Parse for AlignContent {
  416. fn parse(s: ParseStream) -> syn::Result<Self> {
  417. let name: HyphenWord = s.parse()?;
  418. if name.try_match("flex-start") {
  419. Ok(AlignContent::FlexStart)
  420. } else if name.try_match("flex-end") {
  421. Ok(AlignContent::FlexEnd)
  422. } else if name.try_match("center") {
  423. Ok(AlignContent::Center)
  424. } else if name.try_match("space-between") {
  425. Ok(AlignContent::SpaceBetween)
  426. } else if name.try_match("space-around") {
  427. Ok(AlignContent::SpaceAround)
  428. } else if name.try_match("stretch") {
  429. Ok(AlignContent::Stretch)
  430. } else {
  431. Err(name.error())
  432. }
  433. }
  434. }
  435. #[test]
  436. fn test_align_content() {
  437. for test in vec![
  438. "flex-start",
  439. "flex-end",
  440. "center",
  441. "space-between",
  442. "space-around",
  443. "stretch",
  444. ] {
  445. assert_eq!(
  446. &syn::parse_str::<AlignContent>(test).unwrap().to_string(),
  447. test
  448. );
  449. }
  450. assert_eq!(
  451. &syn::parse_str::<Style>("align-content:flex-start")
  452. .unwrap()
  453. .to_string(),
  454. "align-content:flex-start"
  455. );
  456. }
  457. impl Parse for AlignItems {
  458. fn parse(s: ParseStream) -> syn::Result<Self> {
  459. let word: HyphenWord = s.parse()?;
  460. if word.try_match("normal") {
  461. Ok(AlignItems::Normal)
  462. } else if word.try_match("stretch") {
  463. Ok(AlignItems::Stretch)
  464. } else if word.try_match("center") {
  465. Ok(AlignItems::Center)
  466. } else if word.try_match("start") {
  467. Ok(AlignItems::Start)
  468. } else if word.try_match("end") {
  469. Ok(AlignItems::End)
  470. } else if word.try_match("flex-start") {
  471. Ok(AlignItems::FlexStart)
  472. } else if word.try_match("flex-end") {
  473. Ok(AlignItems::FlexEnd)
  474. } else if word.try_match("baseline") {
  475. Ok(AlignItems::Baseline)
  476. } else if word.try_match("first") {
  477. let word: HyphenWord = s.parse()?;
  478. if word.try_match("baseline") {
  479. Ok(AlignItems::FirstBaseline)
  480. } else {
  481. Err(word.error())
  482. }
  483. } else if word.try_match("last") {
  484. let word: HyphenWord = s.parse()?;
  485. if word.try_match("baseline") {
  486. Ok(AlignItems::LastBaseline)
  487. } else {
  488. Err(word.error())
  489. }
  490. } else if word.try_match("safe") {
  491. let word: HyphenWord = s.parse()?;
  492. if word.try_match("center") {
  493. Ok(AlignItems::SafeCenter)
  494. } else {
  495. Err(word.error())
  496. }
  497. } else if word.try_match("unsafe") {
  498. let word: HyphenWord = s.parse()?;
  499. if word.try_match("center") {
  500. Ok(AlignItems::UnsafeCenter)
  501. } else {
  502. Err(word.error())
  503. }
  504. } else {
  505. Err(word.error())
  506. }
  507. }
  508. }
  509. impl Parse for AlignSelf {
  510. fn parse(s: ParseStream) -> syn::Result<Self> {
  511. let word: HyphenWord = s.parse()?;
  512. if word.try_match("auto") {
  513. Ok(AlignSelf::Auto)
  514. } else if word.try_match("normal") {
  515. Ok(AlignSelf::Normal)
  516. } else if word.try_match("center") {
  517. Ok(AlignSelf::Center)
  518. } else if word.try_match("start") {
  519. Ok(AlignSelf::Start)
  520. } else if word.try_match("self-start") {
  521. Ok(AlignSelf::SelfStart)
  522. } else if word.try_match("self-end") {
  523. Ok(AlignSelf::SelfEnd)
  524. } else if word.try_match("flex-start") {
  525. Ok(AlignSelf::FlexStart)
  526. } else if word.try_match("flex-end") {
  527. Ok(AlignSelf::FlexEnd)
  528. } else if word.try_match("baseline") {
  529. Ok(AlignSelf::Baseline)
  530. } else if word.try_match("first") {
  531. let word: HyphenWord = s.parse()?;
  532. if word.try_match("baseline") {
  533. Ok(AlignSelf::FirstBaseline)
  534. } else {
  535. Err(word.error())
  536. }
  537. } else if word.try_match("last") {
  538. let word: HyphenWord = s.parse()?;
  539. if word.try_match("baseline") {
  540. Ok(AlignSelf::LastBaseline)
  541. } else {
  542. Err(word.error())
  543. }
  544. } else if word.try_match("stretch") {
  545. Ok(AlignSelf::Stretch)
  546. } else if word.try_match("safe") {
  547. let word: HyphenWord = s.parse()?;
  548. if word.try_match("center") {
  549. Ok(AlignSelf::SafeCenter)
  550. } else {
  551. Err(word.error())
  552. }
  553. } else if word.try_match("unsafe") {
  554. let word: HyphenWord = s.parse()?;
  555. if word.try_match("center") {
  556. Ok(AlignSelf::UnsafeCenter)
  557. } else {
  558. Err(word.error())
  559. }
  560. } else {
  561. Err(word.error())
  562. }
  563. }
  564. }
  565. impl Parse for BackgroundAttachment {
  566. fn parse(s: ParseStream) -> syn::Result<Self> {
  567. let word: HyphenWord = s.parse()?;
  568. if word.try_match("scroll") {
  569. Ok(BackgroundAttachment::Scroll)
  570. } else if word.try_match("fixed") {
  571. Ok(BackgroundAttachment::Fixed)
  572. } else if word.try_match("local") {
  573. Ok(BackgroundAttachment::Local)
  574. } else {
  575. Err(word.error())
  576. }
  577. }
  578. }
  579. impl Parse for BlendMode {
  580. fn parse(s: ParseStream) -> syn::Result<Self> {
  581. let word: HyphenWord = s.parse()?;
  582. if word.try_match("normal") {
  583. Ok(BlendMode::Normal)
  584. } else if word.try_match("multiply") {
  585. Ok(BlendMode::Multiply)
  586. } else if word.try_match("screen") {
  587. Ok(BlendMode::Screen)
  588. } else if word.try_match("overlay") {
  589. Ok(BlendMode::Overlay)
  590. } else if word.try_match("darken") {
  591. Ok(BlendMode::Darken)
  592. } else if word.try_match("lighten") {
  593. Ok(BlendMode::Lighten)
  594. } else if word.try_match("color-dodge") {
  595. Ok(BlendMode::ColorDodge)
  596. } else if word.try_match("color-burn") {
  597. Ok(BlendMode::ColorBurn)
  598. } else if word.try_match("hard-light") {
  599. Ok(BlendMode::HardLight)
  600. } else if word.try_match("soft-light") {
  601. Ok(BlendMode::SoftLight)
  602. } else if word.try_match("difference") {
  603. Ok(BlendMode::Difference)
  604. } else if word.try_match("exclusion") {
  605. Ok(BlendMode::Exclusion)
  606. } else if word.try_match("hue") {
  607. Ok(BlendMode::Hue)
  608. } else if word.try_match("saturation") {
  609. Ok(BlendMode::Saturation)
  610. } else if word.try_match("color") {
  611. Ok(BlendMode::Color)
  612. } else if word.try_match("luminosity") {
  613. Ok(BlendMode::Luminosity)
  614. } else {
  615. Err(word.error())
  616. }
  617. }
  618. }
  619. impl Parse for BackgroundImage {
  620. fn parse(s: ParseStream) -> syn::Result<Self> {
  621. let peek = HyphenWord::peek_specific(s);
  622. if peek.as_ref().map(|s| s.as_str()) == Some("url") {
  623. let url;
  624. syn::parenthesized!(url in s);
  625. let url = url.parse::<syn::LitStr>()?;
  626. Ok(BackgroundImage::Url(url.value()))
  627. } else {
  628. let word: HyphenWord = s.parse()?;
  629. word.add_expected("url");
  630. if word.try_match("none") {
  631. Ok(BackgroundImage::None)
  632. } else {
  633. Err(word.error())
  634. }
  635. }
  636. }
  637. }
  638. impl Parse for BackgroundBox {
  639. fn parse(s: ParseStream) -> syn::Result<Self> {
  640. let word: HyphenWord = s.parse()?;
  641. if word.try_match("border-box") {
  642. Ok(BackgroundBox::BorderBox)
  643. } else if word.try_match("padding-box") {
  644. Ok(BackgroundBox::PaddingBox)
  645. } else if word.try_match("content-box") {
  646. Ok(BackgroundBox::ContentBox)
  647. } else {
  648. Err(word.error())
  649. }
  650. }
  651. }
  652. impl Parse for BackgroundPosition {
  653. fn parse(s: ParseStream) -> syn::Result<Self> {
  654. let word: HyphenWord = s.parse()?;
  655. if word.try_match("top") {
  656. Ok(BackgroundPosition::Top)
  657. } else if word.try_match("bottom") {
  658. Ok(BackgroundPosition::Bottom)
  659. } else if word.try_match("left") {
  660. Ok(BackgroundPosition::Left)
  661. } else if word.try_match("right") {
  662. Ok(BackgroundPosition::Right)
  663. } else if word.try_match("center") {
  664. Ok(BackgroundPosition::Center)
  665. } else {
  666. Err(word.error())
  667. }
  668. }
  669. }
  670. impl Parse for BackgroundRepeat {
  671. fn parse(s: ParseStream) -> syn::Result<Self> {
  672. let word: HyphenWord = s.parse()?;
  673. if word.try_match("repeat-x") {
  674. Ok(BackgroundRepeat::RepeatX)
  675. } else if word.try_match("repeat-y") {
  676. Ok(BackgroundRepeat::RepeatY)
  677. } else if let Ok(v) = s.parse() {
  678. Ok(BackgroundRepeat::SingleOrDouble(v))
  679. } else {
  680. word.add_expected("repeat");
  681. word.add_expected("space");
  682. word.add_expected("round");
  683. word.add_expected("no-repeat");
  684. Err(word.error())
  685. }
  686. }
  687. }
  688. impl Parse for BgRepeatPart {
  689. fn parse(s: ParseStream) -> syn::Result<Self> {
  690. let word: HyphenWord = s.parse()?;
  691. if word.try_match("repeat") {
  692. Ok(BgRepeatPart::Repeat)
  693. } else if word.try_match("space") {
  694. Ok(BgRepeatPart::Space)
  695. } else if word.try_match("round") {
  696. Ok(BgRepeatPart::Round)
  697. } else if word.try_match("no-repeat") {
  698. Ok(BgRepeatPart::NoRepeat)
  699. } else {
  700. Err(word.error())
  701. }
  702. }
  703. }
  704. impl Parse for BackgroundSize {
  705. fn parse(s: ParseStream) -> syn::Result<Self> {
  706. let word: HyphenWord = s.parse()?;
  707. if word.try_match("cover") {
  708. Ok(BackgroundSize::Cover)
  709. } else if word.try_match("contain") {
  710. Ok(BackgroundSize::Contain)
  711. } else if let Ok(v) = s.parse() {
  712. Ok(BackgroundSize::SingleOrDouble(v))
  713. } else {
  714. word.add_expected("<length>");
  715. word.add_expected("<percentage>");
  716. word.add_expected("auto");
  717. Err(word.error())
  718. }
  719. }
  720. }
  721. impl Parse for Border {
  722. fn parse(s: ParseStream) -> syn::Result<Self> {
  723. fn line_width_error(span: Span) -> syn::Error {
  724. syn::Error::new(span, "the border width was specified more than once")
  725. }
  726. fn line_style_error(span: Span) -> syn::Error {
  727. syn::Error::new(span, "the border style was specified more than once")
  728. }
  729. fn color_error(span: Span) -> syn::Error {
  730. syn::Error::new(span, "the border color was specified more than once")
  731. }
  732. let mut border = Border::new();
  733. while !(border.is_full() || finished_rule(s)) {
  734. let mut matched_something = false; // prevents an infinite loop when no matches
  735. let width_fork = s.fork();
  736. match width_fork.parse::<LineWidth>() {
  737. Ok(line_width) => {
  738. if border.has_line_width() {
  739. return Err(line_width_error(width_fork.cursor().span()));
  740. }
  741. matched_something = true;
  742. border.line_width = Some(line_width);
  743. s.advance_to(&width_fork);
  744. }
  745. Err(_) => (),
  746. }
  747. let style_fork = s.fork();
  748. match style_fork.parse::<LineStyle>() {
  749. Ok(line_style) => {
  750. if border.has_line_style() {
  751. return Err(line_style_error(style_fork.cursor().span()));
  752. }
  753. matched_something = true;
  754. border.line_style = Some(line_style);
  755. s.advance_to(&style_fork);
  756. }
  757. Err(_) => (),
  758. }
  759. let color_fork = s.fork();
  760. match color_fork.parse::<Color>() {
  761. Ok(color) => {
  762. if border.has_color() {
  763. return Err(color_error(color_fork.cursor().span()));
  764. }
  765. matched_something = true;
  766. border.color = Some(color);
  767. s.advance_to(&color_fork);
  768. }
  769. Err(_) => (),
  770. }
  771. if !(matched_something || finished_rule(s)) {
  772. return Err(syn::Error::new(
  773. s.cursor().span(),
  774. "unexpected input - expected one of border-width, border-style, color",
  775. ));
  776. }
  777. }
  778. Ok(border)
  779. }
  780. }
  781. #[test]
  782. fn test_border_color() {
  783. for (input, output) in vec![
  784. ("black", Rect::All(Color::Black)),
  785. (
  786. "#fff blue",
  787. Rect::VerticalHorizontal(Color::HexRGB(255, 255, 255), Color::Blue),
  788. ),
  789. (
  790. "blue hsl(20, 5%, 100%) white",
  791. Rect::TopHorizontalBottom(Color::Blue, Color::HSL(20.0, 5.0, 100.0), Color::White),
  792. ),
  793. (
  794. "hsla(20, 5%, 100%, 0.2) #fff #ccc white",
  795. Rect::TopRightBottomLeft(
  796. Color::HSLA(20.0, 5.0, 100.0, 0.2),
  797. Color::HexRGB(255, 255, 255),
  798. Color::HexRGB(204, 204, 204),
  799. Color::White,
  800. ),
  801. ),
  802. ] {
  803. assert_eq!(syn::parse_str::<Rect<Color>>(input).unwrap(), output);
  804. }
  805. }
  806. #[test]
  807. fn test_border_width() {
  808. for (input, output) in vec![
  809. ("1px", BorderWidth::All(LineWidth::Length(Length::Px(1.0)))),
  810. (
  811. "1px 2\"em\"",
  812. BorderWidth::VerticalHorizontal(
  813. LineWidth::Length(Length::Px(1.0)),
  814. LineWidth::Length(Length::Em(2.0)),
  815. ),
  816. ),
  817. (
  818. "2\"em\" medium thick",
  819. BorderWidth::TopHorizontalBottom(
  820. LineWidth::Length(Length::Em(2.0)),
  821. LineWidth::Medium,
  822. LineWidth::Thick,
  823. ),
  824. ),
  825. (
  826. "2\"em\" medium 1px thick",
  827. BorderWidth::TopRightBottomLeft(
  828. LineWidth::Length(Length::Em(2.0)),
  829. LineWidth::Medium,
  830. LineWidth::Length(Length::Px(1.0)),
  831. LineWidth::Thick,
  832. ),
  833. ),
  834. ] {
  835. assert_eq!(syn::parse_str::<BorderWidth>(input).unwrap(), output);
  836. }
  837. for input in vec!["thi", "1px 1px 1px 1px 1px"] {
  838. assert!(syn::parse_str::<BorderWidth>(input).is_err());
  839. }
  840. }
  841. impl Parse for BorderCollapse {
  842. fn parse(s: ParseStream) -> syn::Result<Self> {
  843. let word: HyphenWord = s.parse()?;
  844. if word.try_match("collapse") {
  845. Ok(BorderCollapse::Collapse)
  846. } else if word.try_match("separate") {
  847. Ok(BorderCollapse::Separate)
  848. } else {
  849. Err(word.error())
  850. }
  851. }
  852. }
  853. impl Parse for BoxShadow {
  854. fn parse(s: ParseStream) -> syn::Result<Self> {
  855. syn::custom_keyword!(none);
  856. if s.peek(none) {
  857. s.parse::<none>()?;
  858. Ok(BoxShadow::None)
  859. } else {
  860. Ok(BoxShadow::Shadows(s.parse()?))
  861. }
  862. }
  863. }
  864. impl Parse for BoxSizing {
  865. fn parse(s: ParseStream) -> syn::Result<Self> {
  866. let word: HyphenWord = s.parse()?;
  867. if word.try_match("border-box") {
  868. Ok(BoxSizing::BorderBox)
  869. } else if word.try_match("content-box") {
  870. Ok(BoxSizing::ContentBox)
  871. } else {
  872. Err(word.error())
  873. }
  874. }
  875. }
  876. impl Parse for Clear {
  877. fn parse(s: ParseStream) -> syn::Result<Self> {
  878. let word: HyphenWord = s.parse()?;
  879. if word.try_match("none") {
  880. Ok(Clear::None)
  881. } else if word.try_match("left") {
  882. Ok(Clear::Left)
  883. } else if word.try_match("right") {
  884. Ok(Clear::Right)
  885. } else if word.try_match("both") {
  886. Ok(Clear::Both)
  887. } else if word.try_match("inline-start") {
  888. Ok(Clear::InlineStart)
  889. } else if word.try_match("inline-end") {
  890. Ok(Clear::InlineEnd)
  891. } else {
  892. Err(word.error())
  893. }
  894. }
  895. }
  896. impl Parse for ColumnCount {
  897. fn parse(s: ParseStream) -> syn::Result<Self> {
  898. if s.peek(syn::LitInt) {
  899. Ok(ColumnCount::Fixed(s.parse::<Integer<u32>>()?.into_inner()))
  900. } else {
  901. let word: HyphenWord = s.parse()?;
  902. word.add_expected("integer");
  903. if word.try_match("auto") {
  904. Ok(ColumnCount::Auto)
  905. } else {
  906. Err(word.error())
  907. }
  908. }
  909. }
  910. }
  911. #[test]
  912. fn test_clear() {
  913. for (input, output) in vec![
  914. ("none", Clear::None),
  915. ("left", Clear::Left),
  916. ("right", Clear::Right),
  917. ("both", Clear::Both),
  918. ("inline-start", Clear::InlineStart),
  919. ("inline-end", Clear::InlineEnd),
  920. ] {
  921. assert_eq!(syn::parse_str::<Clear>(input).unwrap(), output);
  922. }
  923. }
  924. impl Parse for Cursor {
  925. fn parse(s: ParseStream) -> syn::Result<Self> {
  926. let word: HyphenWord = s.parse()?;
  927. if word.try_match("auto") {
  928. Ok(Cursor::Auto)
  929. } else if word.try_match("default") {
  930. Ok(Cursor::Default)
  931. } else if word.try_match("none") {
  932. Ok(Cursor::None)
  933. } else if word.try_match("context-menu") {
  934. Ok(Cursor::ContextMenu)
  935. } else if word.try_match("help") {
  936. Ok(Cursor::Help)
  937. } else if word.try_match("pointer") {
  938. Ok(Cursor::Pointer)
  939. } else if word.try_match("progress") {
  940. Ok(Cursor::Progress)
  941. } else if word.try_match("wait") {
  942. Ok(Cursor::Wait)
  943. } else if word.try_match("cell") {
  944. Ok(Cursor::Cell)
  945. } else if word.try_match("crosshair") {
  946. Ok(Cursor::Crosshair)
  947. } else if word.try_match("text") {
  948. Ok(Cursor::Text)
  949. } else if word.try_match("vertical-text") {
  950. Ok(Cursor::VerticalText)
  951. } else if word.try_match("alias") {
  952. Ok(Cursor::Alias)
  953. } else if word.try_match("copy") {
  954. Ok(Cursor::Copy)
  955. } else if word.try_match("move") {
  956. Ok(Cursor::Move)
  957. } else if word.try_match("no-drop") {
  958. Ok(Cursor::NoDrop)
  959. } else if word.try_match("not-allowed") {
  960. Ok(Cursor::NotAllowed)
  961. } else if word.try_match("grab") {
  962. Ok(Cursor::Grab)
  963. } else if word.try_match("grabbing") {
  964. Ok(Cursor::Grabbing)
  965. } else if word.try_match("e-resize") {
  966. Ok(Cursor::EResize)
  967. } else if word.try_match("n-resize") {
  968. Ok(Cursor::NResize)
  969. } else if word.try_match("ne-resize") {
  970. Ok(Cursor::NEResize)
  971. } else if word.try_match("nw-resize") {
  972. Ok(Cursor::NWResize)
  973. } else if word.try_match("s-resize") {
  974. Ok(Cursor::SResize)
  975. } else if word.try_match("se-resize") {
  976. Ok(Cursor::SEResize)
  977. } else if word.try_match("sw-resize") {
  978. Ok(Cursor::SWResize)
  979. } else if word.try_match("w-resize") {
  980. Ok(Cursor::WResize)
  981. } else if word.try_match("ew-resize") {
  982. Ok(Cursor::EWResize)
  983. } else if word.try_match("ns-resize") {
  984. Ok(Cursor::NSResize)
  985. } else if word.try_match("nesw-resize") {
  986. Ok(Cursor::NESWResize)
  987. } else if word.try_match("nwse-resize") {
  988. Ok(Cursor::NWSEResize)
  989. } else if word.try_match("col-resize") {
  990. Ok(Cursor::ColResize)
  991. } else if word.try_match("row-resize") {
  992. Ok(Cursor::RowResize)
  993. } else if word.try_match("all-scroll") {
  994. Ok(Cursor::AllScroll)
  995. } else if word.try_match("zoom-in") {
  996. Ok(Cursor::ZoomIn)
  997. } else if word.try_match("zoom-out") {
  998. Ok(Cursor::ZoomOut)
  999. } else {
  1000. Err(word.error())
  1001. }
  1002. }
  1003. }
  1004. impl Parse for Display {
  1005. fn parse(s: ParseStream) -> syn::Result<Self> {
  1006. let word: HyphenWord = s.parse()?;
  1007. if word.try_match("block") {
  1008. Ok(Display::Block)
  1009. } else if word.try_match("flex") {
  1010. Ok(Display::Flex)
  1011. } else if word.try_match("inline") {
  1012. Ok(Display::Inline)
  1013. } else {
  1014. Err(word.error())
  1015. }
  1016. }
  1017. }
  1018. impl Parse for FlexBasis {
  1019. fn parse(s: ParseStream) -> syn::Result<Self> {
  1020. syn::custom_keyword!(content);
  1021. if s.peek(content) {
  1022. s.parse::<content>()?;
  1023. Ok(FlexBasis::Content)
  1024. } else {
  1025. let w: Width21 = s.parse()?;
  1026. Ok(FlexBasis::Width(w))
  1027. }
  1028. }
  1029. }
  1030. impl Parse for FlexDirection {
  1031. fn parse(s: ParseStream) -> syn::Result<Self> {
  1032. let word: HyphenWord = s.parse()?;
  1033. if word.try_match("column") {
  1034. Ok(FlexDirection::Column)
  1035. } else if word.try_match("row") {
  1036. Ok(FlexDirection::Row)
  1037. } else {
  1038. Err(word.error())
  1039. }
  1040. }
  1041. }
  1042. impl Parse for FlexWrap {
  1043. fn parse(s: ParseStream) -> syn::Result<Self> {
  1044. let word: HyphenWord = s.parse()?;
  1045. if word.try_match("wrap") {
  1046. Ok(FlexWrap::Wrap)
  1047. } else if word.try_match("nowrap") {
  1048. Ok(FlexWrap::Nowrap)
  1049. } else {
  1050. Err(word.error())
  1051. }
  1052. }
  1053. }
  1054. impl Parse for Float {
  1055. fn parse(s: ParseStream) -> syn::Result<Self> {
  1056. let word: HyphenWord = s.parse()?;
  1057. if word.try_match("none") {
  1058. Ok(Float::None)
  1059. } else if word.try_match("left") {
  1060. Ok(Float::Left)
  1061. } else if word.try_match("right") {
  1062. Ok(Float::Right)
  1063. } else if word.try_match("inline-start") {
  1064. Ok(Float::InlineStart)
  1065. } else if word.try_match("inline-end") {
  1066. Ok(Float::InlineEnd)
  1067. } else {
  1068. Err(word.error())
  1069. }
  1070. }
  1071. }
  1072. impl Parse for Font {
  1073. fn parse(s: ParseStream) -> syn::Result<Self> {
  1074. if s.peek(syn::LitStr) {
  1075. Ok(Font::Named(s.parse::<syn::LitStr>()?.value()))
  1076. } else {
  1077. let name: HyphenWord = s.parse()?;
  1078. name.add_expected("named font");
  1079. if name.try_match("serif") {
  1080. Ok(Font::Serif)
  1081. } else if name.try_match("sans-serif") {
  1082. Ok(Font::SansSerif)
  1083. } else if name.try_match("cursive") {
  1084. Ok(Font::Cursive)
  1085. } else if name.try_match("fantasy") {
  1086. Ok(Font::Fantasy)
  1087. } else if name.try_match("monospace") {
  1088. Ok(Font::Fantasy)
  1089. } else {
  1090. Err(name.error())
  1091. }
  1092. }
  1093. }
  1094. }
  1095. #[test]
  1096. fn test_font_family() {
  1097. for (input, output) in vec![
  1098. (
  1099. "cursive",
  1100. FontFamily {
  1101. first: Font::Cursive,
  1102. rest: vec![],
  1103. },
  1104. ),
  1105. (
  1106. "\"Amatic SC\", sans-serif",
  1107. FontFamily {
  1108. first: Font::Named("Amatic SC".to_string()),
  1109. rest: vec![Font::SansSerif],
  1110. },
  1111. ),
  1112. ] {
  1113. assert_eq!(syn::parse_str::<FontFamily>(input).unwrap(), output);
  1114. }
  1115. for val in vec![
  1116. "font-family:\"Font Awesome 5 Free\"",
  1117. "font-family:\"Some Name\",\"Another Name\",serif",
  1118. ] {
  1119. assert_eq!(&syn::parse_str::<Style>(val).unwrap().to_string(), val);
  1120. }
  1121. }
  1122. impl Parse for FontSize {
  1123. fn parse(s: ParseStream) -> syn::Result<Self> {
  1124. let word_fork = s.fork();
  1125. let name: HyphenWord = word_fork.parse()?;
  1126. if name.try_match("xx-small") {
  1127. s.advance_to(&word_fork);
  1128. Ok(FontSize::XXSmall)
  1129. } else if name.try_match("x-small") {
  1130. s.advance_to(&word_fork);
  1131. Ok(FontSize::XSmall)
  1132. } else if name.try_match("small") {
  1133. s.advance_to(&word_fork);
  1134. Ok(FontSize::Small)
  1135. } else if name.try_match("medium") {
  1136. s.advance_to(&word_fork);
  1137. Ok(FontSize::Medium)
  1138. } else if name.try_match("large") {
  1139. s.advance_to(&word_fork);
  1140. Ok(FontSize::Large)
  1141. } else if name.try_match("x-large") {
  1142. s.advance_to(&word_fork);
  1143. Ok(FontSize::XLarge)
  1144. } else if name.try_match("xx-large") {
  1145. s.advance_to(&word_fork);
  1146. Ok(FontSize::XXLarge)
  1147. } else if name.try_match("xxx-large") {
  1148. s.advance_to(&word_fork);
  1149. Ok(FontSize::XXXLarge)
  1150. } else if name.try_match("larger") {
  1151. s.advance_to(&word_fork);
  1152. Ok(FontSize::Larger)
  1153. } else if name.try_match("smaller") {
  1154. s.advance_to(&word_fork);
  1155. Ok(FontSize::Smaller)
  1156. } else {
  1157. s.parse().map(FontSize::LengthPercentage).map_err(|_| {
  1158. name.add_expected("length");
  1159. name.add_expected("percentage");
  1160. name.error()
  1161. })
  1162. }
  1163. }
  1164. }
  1165. impl Parse for FontStyle {
  1166. fn parse(s: ParseStream) -> syn::Result<Self> {
  1167. let name: HyphenWord = s.parse()?;
  1168. if name.try_match("normal") {
  1169. Ok(FontStyle::Normal)
  1170. } else if name.try_match("italic") {
  1171. Ok(FontStyle::Italic)
  1172. } else if name.try_match("oblique") {
  1173. Ok(FontStyle::Oblique)
  1174. } else {
  1175. Err(name.error())
  1176. }
  1177. }
  1178. }
  1179. #[test]
  1180. fn test_font_style() {
  1181. for (input, output) in vec![
  1182. ("normal", FontStyle::Normal),
  1183. ("italic", FontStyle::Italic),
  1184. ("oblique", FontStyle::Oblique),
  1185. ] {
  1186. assert_eq!(syn::parse_str::<FontStyle>(input).unwrap(), output);
  1187. }
  1188. for input in vec!["norma", "normal trailing"] {
  1189. assert!(syn::parse_str::<FontStyle>(input).is_err());
  1190. }
  1191. }
  1192. impl Parse for FontWeight {
  1193. fn parse(s: ParseStream) -> syn::Result<Self> {
  1194. let name: HyphenWord = s.parse()?;
  1195. name.add_expected("number where 1 <= number <= 1000");
  1196. if name.try_match("normal") {
  1197. Ok(FontWeight::Normal)
  1198. } else if name.try_match("bold") {
  1199. Ok(FontWeight::Bold)
  1200. } else if name.try_match("lighter") {
  1201. Ok(FontWeight::Lighter)
  1202. } else if name.try_match("bolder") {
  1203. Ok(FontWeight::Bolder)
  1204. } else {
  1205. let n: Number = s.parse().map_err(|_| name.error())?;
  1206. if n.suffix.is_empty() && n.value >= 1.0 && n.value <= 1000.0 {
  1207. Ok(FontWeight::Number(n.value))
  1208. } else {
  1209. Err(name.error())
  1210. }
  1211. }
  1212. }
  1213. }
  1214. #[test]
  1215. fn test_font_weight() {
  1216. for (input, output) in vec![
  1217. ("normal", FontWeight::Normal),
  1218. ("bold", FontWeight::Bold),
  1219. ("lighter", FontWeight::Lighter),
  1220. ("bolder", FontWeight::Bolder),
  1221. ("1", FontWeight::Number(1.0)),
  1222. ("1.0", FontWeight::Number(1.0)),
  1223. ("1000", FontWeight::Number(1000.0)),
  1224. ("1000.0", FontWeight::Number(1000.0)),
  1225. ("246.15", FontWeight::Number(246.15)),
  1226. ] {
  1227. match syn::parse_str::<FontWeight>(input) {
  1228. Ok(v) => assert_eq!(v, output),
  1229. Err(e) => panic!("error parsing {}: {}", input, e),
  1230. }
  1231. }
  1232. }
  1233. impl Parse for JustifyContent {
  1234. fn parse(s: ParseStream) -> syn::Result<Self> {
  1235. let name: HyphenWord = s.parse()?;
  1236. if name.try_match("flex-start") {
  1237. Ok(JustifyContent::FlexStart)
  1238. } else if name.try_match("flex-end") {
  1239. Ok(JustifyContent::FlexEnd)
  1240. } else if name.try_match("center") {
  1241. Ok(JustifyContent::Center)
  1242. } else if name.try_match("space-between") {
  1243. Ok(JustifyContent::SpaceBetween)
  1244. } else if name.try_match("space-around") {
  1245. Ok(JustifyContent::SpaceAround)
  1246. } else if name.try_match("start") {
  1247. // - not in level 1 spec
  1248. Ok(JustifyContent::FlexStart)
  1249. } else if name.try_match("end") {
  1250. // - not in level 1 spec
  1251. Ok(JustifyContent::FlexEnd)
  1252. } else {
  1253. Err(name.error())
  1254. }
  1255. }
  1256. }
  1257. impl Parse for Length {
  1258. fn parse(s: ParseStream) -> syn::Result<Self> {
  1259. let neg = if s.peek(Token![-]) {
  1260. s.parse::<Token![-]>()?;
  1261. true
  1262. } else {
  1263. false
  1264. };
  1265. let n: Number = s.parse()?;
  1266. Length::parse_from_number(n, neg)
  1267. }
  1268. }
  1269. impl Length {
  1270. fn parse_from_number(n: Number, neg: bool) -> syn::Result<Self> {
  1271. let neg = if neg { -1.0 } else { 1.0 };
  1272. if n.suffix == "em" {
  1273. Ok(Length::Em(n.value * neg))
  1274. } else if n.suffix == "ex" {
  1275. Ok(Length::Ex(n.value * neg))
  1276. } else if n.suffix == "in" {
  1277. Ok(Length::In(n.value * neg))
  1278. } else if n.suffix == "cm" {
  1279. Ok(Length::Cm(n.value * neg))
  1280. } else if n.suffix == "mm" {
  1281. Ok(Length::Mm(n.value * neg))
  1282. } else if n.suffix == "pt" {
  1283. Ok(Length::Pt(n.value * neg))
  1284. } else if n.suffix == "pc" {
  1285. Ok(Length::Pc(n.value * neg))
  1286. } else if n.suffix == "px" {
  1287. Ok(Length::Px(n.value * neg))
  1288. } else if n.suffix == "" && n.value == 0.0 {
  1289. Ok(Length::Zero)
  1290. } else {
  1291. // No matches so return error
  1292. Err(syn::Error::new(
  1293. n.span,
  1294. "expected one of `\"em\"`, `\"ex\"`, `in`, `cm`, `mm`, `pt`, `pc`, `px` after number, or 0",
  1295. ))
  1296. }
  1297. }
  1298. }
  1299. impl Parse for LineStyle {
  1300. fn parse(s: ParseStream) -> syn::Result<Self> {
  1301. let name = s.parse::<HyphenWord>()?;
  1302. if name.try_match("none") {
  1303. Ok(LineStyle::None)
  1304. } else if name.try_match("hidden") {
  1305. Ok(LineStyle::Hidden)
  1306. } else if name.try_match("dotted") {
  1307. Ok(LineStyle::Dotted)
  1308. } else if name.try_match("dashed") {
  1309. Ok(LineStyle::Dashed)
  1310. } else if name.try_match("solid") {
  1311. Ok(LineStyle::Solid)
  1312. } else if name.try_match("double") {
  1313. Ok(LineStyle::Double)
  1314. } else if name.try_match("groove") {
  1315. Ok(LineStyle::Groove)
  1316. } else if name.try_match("ridge") {
  1317. Ok(LineStyle::Ridge)
  1318. } else if name.try_match("inset") {
  1319. Ok(LineStyle::Inset)
  1320. } else if name.try_match("outset") {
  1321. Ok(LineStyle::Outset)
  1322. } else {
  1323. Err(name.error())
  1324. }
  1325. }
  1326. }
  1327. impl Parse for LineWidth {
  1328. fn parse(s: ParseStream) -> syn::Result<Self> {
  1329. let name = s.parse::<HyphenWord>()?;
  1330. if name.try_match("thin") {
  1331. Ok(LineWidth::Thin)
  1332. } else if name.try_match("medium") {
  1333. Ok(LineWidth::Medium)
  1334. } else if name.try_match("thick") {
  1335. Ok(LineWidth::Thick)
  1336. } else {
  1337. match s.parse::<Length>() {
  1338. Ok(l) => Ok(LineWidth::Length(l)),
  1339. Err(_) => {
  1340. name.add_expected("length");
  1341. Err(name.error())
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. #[test]
  1348. fn test_parse_line_width() {
  1349. assert_eq!(
  1350. syn::parse_str::<LineWidth>("thin").unwrap(),
  1351. LineWidth::Thin
  1352. );
  1353. }
  1354. impl Parse for LineHeight {
  1355. fn parse(s: ParseStream) -> syn::Result<Self> {
  1356. Ok(LineHeight(s.parse::<syn::LitFloat>()?.base10_parse()?))
  1357. }
  1358. }
  1359. impl Parse for ListStyleType {
  1360. fn parse(s: ParseStream) -> syn::Result<Self> {
  1361. let name: HyphenWord = s.parse()?;
  1362. if name.try_match("disc") {
  1363. Ok(ListStyleType::Disc)
  1364. } else if name.try_match("circle") {
  1365. Ok(ListStyleType::Circle)
  1366. } else if name.try_match("square") {
  1367. Ok(ListStyleType::Square)
  1368. } else if name.try_match("decimal") {
  1369. Ok(ListStyleType::Decimal)
  1370. } else if name.try_match("decimal-leading-zero") {
  1371. Ok(ListStyleType::DecimalLeadingZero)
  1372. } else if name.try_match("lower-roman") {
  1373. Ok(ListStyleType::LowerRoman)
  1374. } else if name.try_match("upper-roman") {
  1375. Ok(ListStyleType::UpperRoman)
  1376. } else if name.try_match("lower-greek") {
  1377. Ok(ListStyleType::LowerGreek)
  1378. } else if name.try_match("upper-greek") {
  1379. Ok(ListStyleType::UpperGreek)
  1380. } else if name.try_match("lower-latin") {
  1381. Ok(ListStyleType::LowerLatin)
  1382. } else if name.try_match("upper-latin") {
  1383. Ok(ListStyleType::UpperLatin)
  1384. } else if name.try_match("armenian") {
  1385. Ok(ListStyleType::Armenian)
  1386. } else if name.try_match("georgian") {
  1387. Ok(ListStyleType::Georgian)
  1388. } else if name.try_match("lower-alpha") {
  1389. Ok(ListStyleType::LowerAlpha)
  1390. } else if name.try_match("upper-alpha") {
  1391. Ok(ListStyleType::UpperAlpha)
  1392. } else if name.try_match("none") {
  1393. Ok(ListStyleType::None)
  1394. } else {
  1395. Err(name.error())
  1396. }
  1397. }
  1398. }
  1399. impl Parse for MaxWidthHeight {
  1400. fn parse(s: ParseStream) -> syn::Result<Self> {
  1401. let name = s.parse::<HyphenWord>()?;
  1402. name.add_expected("length");
  1403. name.add_expected("percentage");
  1404. if name.try_match("none") {
  1405. Ok(MaxWidthHeight::None)
  1406. } else if name.try_match("min-content") {
  1407. Ok(MaxWidthHeight::MinContent)
  1408. } else if name.try_match("max-content") {
  1409. Ok(MaxWidthHeight::MaxContent)
  1410. } else if name.try_match("fit-content") {
  1411. let content;
  1412. syn::parenthesized!(content in s);
  1413. Ok(MaxWidthHeight::FitContent(content.parse()?))
  1414. } else {
  1415. s.parse()
  1416. .map(|lp| MaxWidthHeight::LengthPercentage(lp))
  1417. .map_err(|_| name.error())
  1418. }
  1419. }
  1420. }
  1421. #[test]
  1422. fn test_max_width_height() {
  1423. let style: Style = syn::parse_str("max-width: 200px").unwrap();
  1424. assert_eq!(&style.to_string(), "max-width:200px");
  1425. }
  1426. impl<T> Parse for Rect<T>
  1427. where
  1428. T: Parse,
  1429. {
  1430. fn parse(s: ParseStream) -> syn::Result<Self> {
  1431. let first = s.parse::<T>()?;
  1432. let fork = s.fork();
  1433. let second = match fork.parse::<T>() {
  1434. Ok(v) => {
  1435. s.advance_to(&fork);
  1436. v
  1437. }
  1438. Err(_) => return Ok(Rect::All(first)),
  1439. };
  1440. let third = match fork.parse::<T>() {
  1441. Ok(v) => {
  1442. s.advance_to(&fork);
  1443. v
  1444. }
  1445. Err(_) => return Ok(Rect::VerticalHorizontal(first, second)),
  1446. };
  1447. match fork.parse::<T>() {
  1448. Ok(v) => {
  1449. s.advance_to(&fork);
  1450. Ok(Rect::TopRightBottomLeft(first, second, third, v))
  1451. }
  1452. Err(_) => Ok(Rect::TopHorizontalBottom(first, second, third)),
  1453. }
  1454. }
  1455. }
  1456. impl Parse for AutoLengthPercentage {
  1457. fn parse(s: ParseStream) -> syn::Result<Self> {
  1458. syn::custom_keyword!(auto);
  1459. if s.peek(auto) {
  1460. s.parse::<auto>()?;
  1461. Ok(AutoLengthPercentage::Auto)
  1462. } else {
  1463. Ok(AutoLengthPercentage::LengthPercentage(s.parse()?))
  1464. }
  1465. }
  1466. }
  1467. impl Parse for ObjectFit {
  1468. fn parse(s: ParseStream) -> syn::Result<Self> {
  1469. let name: HyphenWord = s.parse()?;
  1470. if name.try_match("fill") {
  1471. Ok(ObjectFit::Fill)
  1472. } else if name.try_match("none") {
  1473. Ok(ObjectFit::None)
  1474. } else if name.try_match("contain") {
  1475. if s.is_empty() {
  1476. Ok(ObjectFit::Contain { scale_down: false })
  1477. } else {
  1478. let scale_down_word: HyphenWord = s.parse()?;
  1479. if scale_down_word.try_match("scale-down") {
  1480. Ok(ObjectFit::Contain { scale_down: true })
  1481. } else {
  1482. Err(scale_down_word.error())
  1483. }
  1484. }
  1485. } else if name.try_match("cover") {
  1486. if HyphenWord::peek(s) {
  1487. let scale_down_word: HyphenWord = s.parse()?;
  1488. if scale_down_word.try_match("scale-down") {
  1489. Ok(ObjectFit::Cover { scale_down: true })
  1490. } else {
  1491. Err(scale_down_word.error())
  1492. }
  1493. } else {
  1494. Ok(ObjectFit::Cover { scale_down: false })
  1495. }
  1496. } else if name.try_match("scale-down") {
  1497. if HyphenWord::peek(s) {
  1498. let cover_contain: HyphenWord = s.parse()?;
  1499. if cover_contain.try_match("cover") {
  1500. Ok(ObjectFit::Cover { scale_down: true })
  1501. } else if cover_contain.try_match("contain") {
  1502. Ok(ObjectFit::Contain { scale_down: true })
  1503. } else {
  1504. Err(cover_contain.error())
  1505. }
  1506. } else {
  1507. // defaults to contain when cover/contain not present
  1508. Ok(ObjectFit::Contain { scale_down: true })
  1509. }
  1510. } else {
  1511. Err(name.error())
  1512. }
  1513. }
  1514. }
  1515. impl Parse for Overflow {
  1516. fn parse(s: ParseStream) -> syn::Result<Self> {
  1517. let first = s.parse::<OverflowXY>()?;
  1518. Ok(match s.parse::<OverflowXY>() {
  1519. Ok(second) => Overflow::XY(first, second),
  1520. Err(_) => Overflow::Both(first),
  1521. })
  1522. }
  1523. }
  1524. impl Parse for OverflowXY {
  1525. fn parse(s: ParseStream) -> syn::Result<Self> {
  1526. let name: HyphenWord = s.parse()?;
  1527. if name.try_match("visible") {
  1528. Ok(OverflowXY::Visible)
  1529. } else if name.try_match("hidden") {
  1530. Ok(OverflowXY::Hidden)
  1531. } else if name.try_match("clip") {
  1532. Ok(OverflowXY::Clip)
  1533. } else if name.try_match("scroll") {
  1534. Ok(OverflowXY::Scroll)
  1535. } else if name.try_match("auto") {
  1536. Ok(OverflowXY::Auto)
  1537. } else {
  1538. Err(name.error())
  1539. }
  1540. }
  1541. }
  1542. impl Parse for Position {
  1543. fn parse(s: ParseStream) -> syn::Result<Self> {
  1544. let name: HyphenWord = s.parse()?;
  1545. if name.try_match("static") {
  1546. Ok(Position::Static)
  1547. } else if name.try_match("relative") {
  1548. Ok(Position::Relative)
  1549. } else if name.try_match("absolute") {
  1550. Ok(Position::Absolute)
  1551. } else if name.try_match("fixed") {
  1552. Ok(Position::Fixed)
  1553. } else {
  1554. Err(name.error())
  1555. }
  1556. }
  1557. }
  1558. #[test]
  1559. fn test_padding() {
  1560. for (input, output) in vec![(
  1561. "padding:1\"em\"",
  1562. Style::Padding(Padding::All(Calc::Normal(LengthPercentage::Length(
  1563. Length::Em(1.0),
  1564. )))),
  1565. )] {
  1566. assert_eq!(syn::parse_str::<Style>(input).unwrap(), output);
  1567. }
  1568. }
  1569. impl Parse for Percentage {
  1570. fn parse(s: ParseStream) -> syn::Result<Self> {
  1571. let n: Number = s.parse()?;
  1572. if n.suffix == "%" {
  1573. Ok(Percentage(n.value))
  1574. } else {
  1575. Err(syn::Error::new(n.span, "expected percentage"))
  1576. }
  1577. }
  1578. }
  1579. impl Parse for WhiteSpace {
  1580. fn parse(s: ParseStream) -> syn::Result<Self> {
  1581. let name: HyphenWord = s.parse()?;
  1582. if name.try_match("normal") {
  1583. Ok(WhiteSpace::Normal)
  1584. } else if name.try_match("pre") {
  1585. Ok(WhiteSpace::Pre)
  1586. } else if name.try_match("nowrap") {
  1587. Ok(WhiteSpace::Nowrap)
  1588. } else if name.try_match("pre-wrap") {
  1589. Ok(WhiteSpace::PreWrap)
  1590. } else if name.try_match("pre-line") {
  1591. Ok(WhiteSpace::PreLine)
  1592. } else {
  1593. Err(name.error())
  1594. }
  1595. }
  1596. }
  1597. impl Parse for Width21 {
  1598. fn parse(s: ParseStream) -> syn::Result<Self> {
  1599. syn::custom_keyword!(auto);
  1600. if s.peek(auto) {
  1601. s.parse::<auto>()?;
  1602. Ok(Width21::Auto)
  1603. } else {
  1604. Ok(Width21::LengthPercentage(s.parse()?))
  1605. }
  1606. }
  1607. }
  1608. impl Parse for WidthHeight {
  1609. fn parse(s: ParseStream) -> syn::Result<Self> {
  1610. let fork = s.fork();
  1611. let name: HyphenWord = fork.parse()?;
  1612. if name.try_match("auto") {
  1613. s.advance_to(&fork);
  1614. Ok(WidthHeight::Auto)
  1615. } else if name.try_match("min-content") {
  1616. s.advance_to(&fork);
  1617. Ok(WidthHeight::MinContent)
  1618. } else if name.try_match("max-content") {
  1619. s.advance_to(&fork);
  1620. Ok(WidthHeight::MaxContent)
  1621. } else if name.try_match("fit-content") {
  1622. s.advance_to(&fork);
  1623. let content;
  1624. syn::parenthesized!(content in s);
  1625. let lp = content.parse()?;
  1626. if !content.is_empty() {
  1627. Err(content.error("trailing tokens"))
  1628. } else {
  1629. Ok(WidthHeight::FitContent(lp))
  1630. }
  1631. } else {
  1632. // todo error message
  1633. Ok(WidthHeight::LengthPercentage(s.parse()?))
  1634. }
  1635. }
  1636. }
  1637. #[test]
  1638. fn test_width_height() {
  1639. for (input, output) in vec![
  1640. ("0", "0"),
  1641. ("1px", "1px"),
  1642. ("1\"em\"", "1em"),
  1643. ("calc(100% - 60px)", "calc(100% - 60px)"),
  1644. ] {
  1645. match syn::parse_str::<WidthHeight>(input) {
  1646. Ok(v) => assert_eq!(&v.to_string(), output),
  1647. Err(e) => panic!("Error in \"{}\": {}", input, e),
  1648. }
  1649. }
  1650. }
  1651. impl Parse for LengthPercentage {
  1652. fn parse(s: ParseStream) -> syn::Result<Self> {
  1653. if s.peek2(Token![%]) {
  1654. Ok(LengthPercentage::Percentage(s.parse()?))
  1655. } else {
  1656. Ok(LengthPercentage::Length(s.parse()?))
  1657. }
  1658. }
  1659. }
  1660. #[test]
  1661. fn test_length_percentage() {
  1662. for (input, output) in vec![
  1663. ("1\"em\"", LengthPercentage::Length(Length::Em(1.0))),
  1664. ("1.0px", LengthPercentage::Length(Length::Px(1.0))),
  1665. ("0", LengthPercentage::Length(Length::Zero)),
  1666. ] {
  1667. assert_eq!(syn::parse_str::<LengthPercentage>(input).unwrap(), output);
  1668. }
  1669. }
  1670. impl Parse for Resize {
  1671. fn parse(s: ParseStream) -> syn::Result<Self> {
  1672. let name: HyphenWord = s.parse()?;
  1673. if name.try_match("none") {
  1674. Ok(Resize::None)
  1675. } else if name.try_match("both") {
  1676. Ok(Resize::Both)
  1677. } else if name.try_match("horizontal") {
  1678. Ok(Resize::Horizontal)
  1679. } else if name.try_match("vertical") {
  1680. Ok(Resize::Vertical)
  1681. } else {
  1682. Err(name.error())
  1683. }
  1684. }
  1685. }
  1686. impl Parse for Shadow {
  1687. fn parse(s: ParseStream) -> syn::Result<Self> {
  1688. syn::custom_keyword!(inset);
  1689. let mut inset_val = false;
  1690. let mut length: Option<ShadowLength> = None;
  1691. let mut color: Option<Color> = None;
  1692. // keep trying all three until we're done or there is an error
  1693. loop {
  1694. let mut parsed_something = false;
  1695. // inset (easiest)
  1696. if s.peek(inset) {
  1697. let inset_tok = s.parse::<inset>()?;
  1698. if inset_val {
  1699. return Err(syn::Error::new(
  1700. inset_tok.span(),
  1701. "`inset` must be specified 0 or 1 times",
  1702. ));
  1703. }
  1704. inset_val = true;
  1705. parsed_something = true;
  1706. }
  1707. // color
  1708. let fork = s.fork();
  1709. if let Ok(parsed_color) = fork.parse::<Color>() {
  1710. if color.is_some() {
  1711. return Err(s.error("color must be specified 0 or 1 times"));
  1712. }
  1713. color = Some(parsed_color);
  1714. s.advance_to(&fork);
  1715. parsed_something = true;
  1716. }
  1717. // length
  1718. let fork = s.fork();
  1719. if let Ok(parsed_length) = fork.parse::<ShadowLength>() {
  1720. if length.is_some() {
  1721. return Err(s.error("shadow length must be specified once"));
  1722. }
  1723. length = Some(parsed_length);
  1724. s.advance_to(&fork);
  1725. parsed_something = true;
  1726. }
  1727. // if we've failed to parse anything, end the loop.
  1728. if !parsed_something {
  1729. break;
  1730. }
  1731. }
  1732. if let Some(length) = length {
  1733. Ok(Shadow {
  1734. color,
  1735. length,
  1736. inset: inset_val,
  1737. })
  1738. } else {
  1739. Err(s.error("expected color, length, or `inset`"))
  1740. }
  1741. }
  1742. }
  1743. impl Parse for ShadowLength {
  1744. fn parse(s: ParseStream) -> syn::Result<Self> {
  1745. let horizontal: Length = s.parse()?;
  1746. let vertical: Length = s.parse()?;
  1747. // blur
  1748. let fork = s.fork();
  1749. let blur = match fork.parse::<Length>() {
  1750. Ok(blur) => {
  1751. s.advance_to(&fork);
  1752. blur
  1753. }
  1754. Err(_) => {
  1755. return Ok(ShadowLength::Offsets {
  1756. horizontal,
  1757. vertical,
  1758. });
  1759. }
  1760. };
  1761. // spread
  1762. let fork = s.fork();
  1763. match fork.parse::<Length>() {
  1764. Ok(spread) => {
  1765. s.advance_to(&fork);
  1766. Ok(ShadowLength::OffsetsBlurSpread {
  1767. horizontal,
  1768. vertical,
  1769. blur,
  1770. spread,
  1771. })
  1772. }
  1773. Err(_) => Ok(ShadowLength::OffsetsBlur {
  1774. horizontal,
  1775. vertical,
  1776. blur,
  1777. }),
  1778. }
  1779. }
  1780. }
  1781. impl Parse for TextAlign {
  1782. fn parse(s: ParseStream) -> syn::Result<Self> {
  1783. let word: HyphenWord = s.parse()?;
  1784. if word.try_match("left") {
  1785. Ok(TextAlign::Left)
  1786. } else if word.try_match("right") {
  1787. Ok(TextAlign::Right)
  1788. } else if word.try_match("center") {
  1789. Ok(TextAlign::Center)
  1790. } else if word.try_match("justify") {
  1791. Ok(TextAlign::Justify)
  1792. } else {
  1793. Err(word.error())
  1794. }
  1795. }
  1796. }
  1797. // color
  1798. // =====
  1799. impl Parse for DynamicColor {
  1800. fn parse(s: ParseStream) -> syn::Result<Self> {
  1801. Ok(if s.peek(syn::token::Brace) {
  1802. DynamicColor::Dynamic(s.parse()?)
  1803. } else {
  1804. DynamicColor::Literal(s.parse()?)
  1805. })
  1806. }
  1807. }
  1808. impl Parse for Color {
  1809. fn parse(s: ParseStream) -> syn::Result<Self> {
  1810. if s.peek(Token![#]) {
  1811. return parse_hex_color(s);
  1812. }
  1813. let fn_name: HyphenWord = s.parse()?;
  1814. if fn_name.try_match("hsl") {
  1815. parse_hsl_color(s, false)
  1816. } else if fn_name.try_match("hsla") {
  1817. parse_hsl_color(s, true)
  1818. } else {
  1819. if let Some(name) = fn_name.word.as_ref() {
  1820. if let Some(color) = Color::from_named(name) {
  1821. return Ok(color);
  1822. }
  1823. }
  1824. fn_name.add_expected("named color");
  1825. Err(fn_name.error())
  1826. }
  1827. }
  1828. }
  1829. fn parse_hex_color(s: ParseStream) -> syn::Result<Color> {
  1830. const ERR_MSG: &'static str = "to avoid confusing rust, please enclose hex colors in `\"`";
  1831. s.parse::<Token![#]>()?;
  1832. if !(s.peek(syn::LitStr) || s.peek(Ident)) {
  1833. return Err(s.error(ERR_MSG));
  1834. }
  1835. if s.peek(syn::LitStr) {
  1836. let hex_str: syn::LitStr = s.parse()?;
  1837. color::parse_hex(&hex_str.value()).ok_or(syn::Error::new(hex_str.span(), ERR_MSG))
  1838. } else {
  1839. let hex_str: Ident = s.parse()?;
  1840. color::parse_hex(&hex_str.to_string()).ok_or(syn::Error::new(hex_str.span(), ERR_MSG))
  1841. }
  1842. }
  1843. fn parse_hsl_color(s: ParseStream, with_alpha: bool) -> syn::Result<Color> {
  1844. let content;
  1845. syn::parenthesized!(content in s);
  1846. let n: Number = content.parse()?;
  1847. n.empty_suffix()?;
  1848. let hue = n.value;
  1849. if hue < 0.0 || hue >= 360.0 {
  1850. return Err(syn::Error::new(
  1851. n.span,
  1852. "hue should be in the range `0 <= hue < 360`",
  1853. ));
  1854. }
  1855. content.parse::<Token![,]>()?;
  1856. let n: Number = content.parse()?;
  1857. if n.suffix != "%" {
  1858. return Err(syn::Error::new(
  1859. n.span,
  1860. "saturation should be a percentage (followed by `%`)",
  1861. ));
  1862. }
  1863. let sat = n.value;
  1864. if sat < 0.0 || sat > 100.0 {
  1865. return Err(syn::Error::new(
  1866. n.span,
  1867. "saturation should be in the range `0 <= sat < 100`",
  1868. ));
  1869. }
  1870. content.parse::<Token![,]>()?;
  1871. let n: Number = content.parse()?;
  1872. if n.suffix != "%" {
  1873. return Err(syn::Error::new(
  1874. n.span,
  1875. "saturation should be a percentage (followed by `%`)",
  1876. ));
  1877. }
  1878. let light = n.value;
  1879. if light < 0.0 || light > 100.0 {
  1880. return Err(syn::Error::new(
  1881. n.span,
  1882. "lightness should be in the range `0 <= light < 100`",
  1883. ));
  1884. }
  1885. // since we parse content in parentheses, we can assume no trailing characers
  1886. if !with_alpha {
  1887. return if content.is_empty() {
  1888. Ok(Color::HSL(hue, sat, light))
  1889. } else {
  1890. Err(content.error("trailing characters"))
  1891. };
  1892. }
  1893. // we are a hsla
  1894. content.parse::<Token![,]>()?;
  1895. let n: Number = content.parse()?;
  1896. n.empty_suffix()?;
  1897. let alpha = n.value;
  1898. if alpha < 0.0 || alpha > 1.0 {
  1899. return Err(syn::Error::new(
  1900. n.span,
  1901. "alpha should be in the range `0 <= alpha < 1`",
  1902. ));
  1903. }
  1904. if content.is_empty() {
  1905. Ok(Color::HSLA(hue, sat, light, alpha))
  1906. } else {
  1907. Err(content.error("unexpected trailing characters"))
  1908. }
  1909. }
  1910. #[test]
  1911. fn test_color() {
  1912. for (input, output) in vec![
  1913. ("#ffffffff", Color::HexRGBA(255, 255, 255, 255)),
  1914. ("#ffffff", Color::HexRGB(255, 255, 255)),
  1915. ("#fff", Color::HexRGB(255, 255, 255)),
  1916. ("#\"fff\"", Color::HexRGB(255, 255, 255)),
  1917. ("hsl(100, 50%, 50%)", Color::HSL(100.0, 50.0, 50.0)),
  1918. ("hsla(60, 0%, 0%, 0.2)", Color::HSLA(60.0, 0.0, 0.0, 0.2)),
  1919. ("black", Color::Black),
  1920. ("yellow", Color::Yellow),
  1921. ] {
  1922. match syn::parse_str::<Color>(input) {
  1923. Ok(c) => assert_eq!(c, output),
  1924. Err(e) => panic!("error parsing color {}: {}", input, e),
  1925. }
  1926. }
  1927. }
  1928. // Util
  1929. // ====
  1930. impl<T> Parse for NonemptyCommaList<T>
  1931. where
  1932. T: Parse,
  1933. {
  1934. fn parse(s: ParseStream) -> syn::Result<Self> {
  1935. let punctuated = Punctuated::<T, Token![,]>::parse_separated_nonempty(s)?;
  1936. let mut iter = punctuated.into_iter();
  1937. let first = iter.next().unwrap();
  1938. Ok(Self {
  1939. first,
  1940. rest: iter.collect(),
  1941. })
  1942. }
  1943. }
  1944. impl<T> Parse for SingleOrDouble<T>
  1945. where
  1946. T: Parse,
  1947. {
  1948. fn parse(s: ParseStream) -> syn::Result<Self> {
  1949. let first = T::parse(s)?;
  1950. let fork = s.fork();
  1951. Ok(match T::parse(&fork) {
  1952. Ok(second) => {
  1953. s.advance_to(&fork);
  1954. SingleOrDouble::Double {
  1955. vert: first,
  1956. horiz: second,
  1957. }
  1958. }
  1959. Err(_) => SingleOrDouble::Single(first),
  1960. })
  1961. }
  1962. }
  1963. /// Either a float or an int, converted in either case to f64.
  1964. ///
  1965. /// A trailing percent (`%`) character will be consumed if the number has no suffix. This is valid
  1966. /// according to the CSS tokeniser spec.
  1967. ///
  1968. /// TODO This only works for floats for now. Although JS only supports floats, integer literals are
  1969. /// used in css.
  1970. #[derive(Debug)]
  1971. struct Number {
  1972. value: f64,
  1973. suffix: String,
  1974. span: Span,
  1975. }
  1976. impl Number {
  1977. fn empty_suffix(&self) -> syn::Result<()> {
  1978. if self.suffix != "" {
  1979. Err(syn::Error::new(
  1980. self.span,
  1981. "unexpected characters after number",
  1982. ))
  1983. } else {
  1984. Ok(())
  1985. }
  1986. }
  1987. #[cfg(test)]
  1988. fn check_value(&self, value: f64, suffix: &str) -> bool {
  1989. self.value == value && self.suffix == suffix
  1990. }
  1991. }
  1992. impl Parse for Number {
  1993. fn parse(s: ParseStream) -> syn::Result<Number> {
  1994. let lookahead = s.lookahead1();
  1995. let (value, mut span, mut suffix) = if lookahead.peek(syn::LitFloat) {
  1996. let tok = s.parse::<syn::LitFloat>()?;
  1997. let num = tok.base10_parse()?;
  1998. (num, tok.span(), tok.suffix().to_string())
  1999. } else if lookahead.peek(syn::LitInt) {
  2000. let tok = s.parse::<syn::LitInt>()?;
  2001. // u32 chosen because it can be safely converted into f64
  2002. let num = tok.base10_parse::<u32>()?;
  2003. (num.into(), tok.span(), tok.suffix().to_string())
  2004. } else {
  2005. return Err(lookahead.error());
  2006. };
  2007. if suffix.is_empty() {
  2008. // look for a `%` for the suffix
  2009. if s.peek(Token![%]) {
  2010. let tok = s.parse::<Token![%]>()?;
  2011. if let Some(extra_span) = span.join(tok.span) {
  2012. span = extra_span;
  2013. }
  2014. suffix.push('%');
  2015. // work-around using literal strings because the lexer can't support suffixes beginning
  2016. // with `e` for floats: https://github.com/rust-lang/rust/issues/67544
  2017. } else if s.peek(syn::LitStr) {
  2018. let tok = s.parse::<syn::LitStr>()?;
  2019. if let Some(extra_span) = span.join(tok.span()) {
  2020. span = extra_span;
  2021. }
  2022. suffix.push_str(&tok.value());
  2023. }
  2024. }
  2025. Ok(Number {
  2026. value,
  2027. suffix,
  2028. span,
  2029. })
  2030. }
  2031. }
  2032. #[test]
  2033. fn test_number() {
  2034. for (input, value, suffix) in vec![
  2035. ("200", 200.0, ""),
  2036. ("200.0", 200.0, ""),
  2037. ("0", 0.0, ""),
  2038. ("0in", 0.0, "in"),
  2039. ] {
  2040. assert!(syn::parse_str::<Number>(input)
  2041. .unwrap()
  2042. .check_value(value, suffix),)
  2043. }
  2044. }
  2045. /// Something like `word-separated-hyphens`
  2046. #[derive(Debug)]
  2047. struct HyphenWord {
  2048. pub span: Span,
  2049. pub word: Option<String>,
  2050. /// List of tried matches - for building error.
  2051. tried: TryList,
  2052. }
  2053. impl HyphenWord {
  2054. pub fn new(span: Span, word: String) -> Self {
  2055. HyphenWord {
  2056. span,
  2057. word: Some(word),
  2058. tried: TryList::new(),
  2059. }
  2060. }
  2061. /// This allows HyphenWords to be empty. In this case the token cursor will not advance and the
  2062. /// returned word will be blank.
  2063. pub fn new_no_word(span: Span) -> Self {
  2064. HyphenWord {
  2065. span,
  2066. word: None,
  2067. tried: TryList::new(),
  2068. }
  2069. }
  2070. pub fn try_match(&self, other: &str) -> bool {
  2071. if Some(other) == self.word.as_ref().map(|s| s.as_str()) {
  2072. true
  2073. } else {
  2074. self.tried.add_literal(other);
  2075. false
  2076. }
  2077. }
  2078. pub fn add_expected(&self, ty: &str) {
  2079. self.tried.add(ty);
  2080. }
  2081. /// Panics if there were no calls to `try_match` before calling this function.
  2082. pub fn error(&self) -> syn::Error {
  2083. self.tried.to_error(self.span)
  2084. }
  2085. /// This is cheaper than peek-specific
  2086. pub fn peek(s: ParseStream) -> bool {
  2087. s.peek(Ident)
  2088. }
  2089. /// Peek the next HyphenWord without advancing the parser.
  2090. pub fn peek_specific(s: ParseStream) -> Option<String> {
  2091. let fork = s.fork();
  2092. match HyphenWord::parse(&fork) {
  2093. Ok(hw) => Some(hw.word.unwrap()),
  2094. Err(_) => None,
  2095. }
  2096. }
  2097. }
  2098. impl Parse for HyphenWord {
  2099. fn parse(s: ParseStream) -> syn::Result<Self> {
  2100. let fork = s.fork();
  2101. let first = match fork.call(Ident::parse_any) {
  2102. Ok(v) => {
  2103. s.advance_to(&fork);
  2104. v
  2105. }
  2106. Err(_) => return Ok(HyphenWord::new_no_word(s.cursor().span())),
  2107. };
  2108. let mut word = first.to_string();
  2109. let mut span = first.span();
  2110. // This is potentially unbounded. Probably not be a problem but making a note anyway.
  2111. while s.peek(Token![-]) {
  2112. let hyphen = s.parse::<Token![-]>()?;
  2113. if let Some(joined) = span.join(hyphen.span) {
  2114. span = joined;
  2115. }
  2116. let part = s.call(Ident::parse_any)?;
  2117. write!(word, "-{}", part).unwrap();
  2118. if let Some(joined) = span.join(part.span()) {
  2119. span = joined;
  2120. }
  2121. }
  2122. Ok(HyphenWord::new(span, word))
  2123. }
  2124. }
  2125. #[test]
  2126. fn test_hyphen_word() {
  2127. let word: HyphenWord = syn::parse_str("first-second-third").unwrap();
  2128. assert_eq!(word.word, Some("first-second-third".to_string()));
  2129. assert!(syn::parse_str::<HyphenWord>("first-second-").is_err());
  2130. assert!(syn::parse_str::<HyphenWord>("a a").is_err());
  2131. }
  2132. /// Keeps track of a list of tokens that have been tried.
  2133. #[derive(Debug)]
  2134. pub struct TryList(RefCell<BTreeSet<String>>);
  2135. impl TryList {
  2136. pub fn new() -> Self {
  2137. TryList(RefCell::new(BTreeSet::new()))
  2138. }
  2139. /// Same as add, but with quotes
  2140. pub fn add_literal(&self, lit: &str) {
  2141. self.add(format!("`{}`", lit));
  2142. }
  2143. pub fn add(&self, ty: impl Into<String>) {
  2144. self.0.borrow_mut().insert(ty.into());
  2145. }
  2146. fn to_error(&self, span: Span) -> syn::Error {
  2147. let tried = self.0.borrow();
  2148. let mut iter = tried.iter();
  2149. let start = iter.next().unwrap().to_owned();
  2150. let list = iter.fold(start, |mut acc, itm| {
  2151. write!(acc, ", {}", itm).unwrap();
  2152. acc
  2153. });
  2154. let error_msg = format!("expected one of {}", list);
  2155. syn::Error::new(span, error_msg)
  2156. }
  2157. }
  2158. /// Whether we are at the end of a rule. Either the stream will be empty, or there will be a
  2159. /// semi-colon.
  2160. fn finished_rule(s: ParseStream) -> bool {
  2161. s.is_empty() || s.peek(Token![;])
  2162. }
  2163. // Parsing integers
  2164. #[derive(Debug, PartialEq)]
  2165. struct Integer<T> {
  2166. value: T,
  2167. }
  2168. impl<T> Integer<T> {
  2169. fn into_inner(self) -> T {
  2170. self.value
  2171. }
  2172. }
  2173. impl<T> Parse for Integer<T>
  2174. where
  2175. T: str::FromStr + fmt::Display + PartialOrd<T>,
  2176. <T as str::FromStr>::Err: fmt::Display,
  2177. {
  2178. fn parse(s: ParseStream) -> syn::Result<Self> {
  2179. Ok(Integer {
  2180. value: integer(s, ..)?,
  2181. })
  2182. }
  2183. }
  2184. /// Parse an integer, with an optional allowed range.
  2185. fn integer<T, R>(s: ParseStream, range: R) -> syn::Result<T>
  2186. where
  2187. R: RangeBounds<T> + fmt::Debug,
  2188. T: str::FromStr + fmt::Display + PartialOrd<T>,
  2189. <T as str::FromStr>::Err: fmt::Display,
  2190. {
  2191. let fixed = s.parse::<syn::LitInt>()?;
  2192. let span = fixed.span();
  2193. if fixed.suffix().is_empty() {
  2194. let fixed = fixed.base10_parse()?;
  2195. if range.contains(&fixed) {
  2196. Ok(fixed)
  2197. } else {
  2198. Err(syn::Error::new(
  2199. span,
  2200. format!(
  2201. "expected a number in the range {:?}, found {}",
  2202. range, fixed
  2203. ),
  2204. ))
  2205. }
  2206. } else {
  2207. Err(syn::Error::new(span, "the number should not have a suffix"))
  2208. }
  2209. }
  2210. #[test]
  2211. fn test_parse_integer() {
  2212. let x: Integer<u8> = syn::parse_str("123").unwrap();
  2213. assert_eq!(x.into_inner(), 123);
  2214. let x: syn::Result<Integer<u8>> = syn::parse_str("256");
  2215. assert!(x.is_err());
  2216. }
  2217. // tests
  2218. #[test]
  2219. fn downstream_bug1() {
  2220. let s: Styles = syn::parse_str(
  2221. "display: flex;
  2222. flex-direction: column;
  2223. flex-grow: 1;
  2224. flex-shrink: 0;",
  2225. )
  2226. .unwrap();
  2227. assert_eq!(
  2228. s.rules,
  2229. vec![
  2230. Style::Display(Display::Flex),
  2231. Style::FlexDirection(FlexDirection::Column),
  2232. Style::FlexGrow(1.0),
  2233. Style::FlexShrink(0.0)
  2234. ]
  2235. )
  2236. }
  2237. #[test]
  2238. #[ignore]
  2239. fn inline_logic() {
  2240. todo!()
  2241. }
  2242. #[cfg(test)]
  2243. mod tests {
  2244. use super::*;
  2245. /// Use if you want to test that something parses, but not if it looks the same when
  2246. /// stringified. Example "border: 1px" -> "border:1px" but we still might want to check that
  2247. /// the former parses.
  2248. fn parse(input: &str) -> Style {
  2249. syn::parse_str(input).unwrap()
  2250. }
  2251. /// This function can be used to quickly write tests to check that a parse and a stringify are
  2252. /// opposites.
  2253. fn round_trip_style(input: &str) {
  2254. assert_eq!(&parse(input).to_string(), input);
  2255. }
  2256. #[test]
  2257. fn border_bottom_left_radius() {
  2258. round_trip_style("border-bottom-left-radius:30% 3px");
  2259. }
  2260. #[test]
  2261. fn border_bottom_right_radius() {
  2262. round_trip_style("border-bottom-right-radius:0 0");
  2263. }
  2264. #[test]
  2265. fn border_collapse() {
  2266. round_trip_style("border-collapse:collapse");
  2267. }
  2268. #[test]
  2269. fn border_width() {
  2270. round_trip_style("border-width:1px");
  2271. round_trip_style("border-width:0 2px 50pt 0");
  2272. }
  2273. }