parser.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package mvg
  2. import "fmt"
  3. import "strconv"
  4. /* LL(1) syntax.
  5. COMMANDS -> COMMAND COMMANDS | .
  6. COMMAND -> word PARAMS .
  7. PARAMS -> ws PARAM PARAMS | PARAM.
  8. PARAM -> LIST | ELEM | string | id | word | url.
  9. LIST -> ELEM comma LIST | ELEM .
  10. ELEM -> var | number.
  11. */
  12. type Parser struct {
  13. Name string
  14. Buffer []rune
  15. Index int
  16. Line int
  17. }
  18. func (p *Parser) Error(msg string, extra ...interface{}) Error {
  19. form := "%s:%d:" + msg
  20. args := []interface{}{}
  21. args = append(args, p.Name, p.Line)
  22. args = append(args, extra...)
  23. return Error{fmt.Errorf(form, args...)}
  24. }
  25. func (p *Parser) Peek() rune {
  26. if p.Index > len(p.Buffer) {
  27. return -1
  28. }
  29. ru := p.Buffer[p.Index]
  30. return ru
  31. }
  32. func (p *Parser) Next() rune {
  33. ru := p.Peek()
  34. if ru == -1 {
  35. return ru
  36. }
  37. if ru == '\n' {
  38. p.Line++
  39. }
  40. p.Index++
  41. return ru
  42. }
  43. func (p *Parser) ParseWhile(ok func(r rune, i int) bool, found func(string) Value) Value {
  44. var ru rune
  45. val := []rune{}
  46. start := p.Index
  47. ru = p.Next()
  48. if !ok(ru, p.Index-start) {
  49. return nil
  50. }
  51. val = append(val, ru)
  52. for ; ok(ru, p.Index-start); ru = p.Next() {
  53. val = append(val, ru)
  54. }
  55. if ru == -1 {
  56. return p.Error("Unexpected EOF")
  57. }
  58. return found(string(val))
  59. }
  60. func IsID(r rune, i int) bool {
  61. if (i == 0) && (r == '%') {
  62. return true
  63. }
  64. return IsWord(r, i)
  65. }
  66. func IsWord(r rune, i int) bool {
  67. return (r >= 'a' && r <= 'z') ||
  68. (r >= 'A' && r <= 'Z') ||
  69. r == '_' || r == '-'
  70. }
  71. func IsNumber(r rune, i int) bool {
  72. return (r >= '0' && r <= '9') ||
  73. r == '.'
  74. }
  75. type Value interface {
  76. Eval(gc *GraphicContext) Value
  77. }
  78. type Error struct {
  79. error
  80. }
  81. func (e Error) Eval(gc *GraphicContext) Value {
  82. return e
  83. }
  84. type Word string
  85. func (w Word) Eval(gc *GraphicContext) Value {
  86. return w
  87. }
  88. type ID string
  89. func (i ID) Eval(gc *GraphicContext) Value {
  90. return i
  91. }
  92. func (p *Parser) ParseID() Value {
  93. return p.ParseWhile(IsID, func(res string) Value {
  94. return ID(res[1:len(res)]) // chop off the %
  95. })
  96. }
  97. type Variable string
  98. func IsVariable(r rune, i int) bool {
  99. if (i == 0) && (r == '$') {
  100. return true
  101. }
  102. return IsWord(r, i)
  103. }
  104. func (v Variable) Eval(gc *GraphicContext) Value {
  105. var ok bool
  106. var val Value
  107. for val, ok = gc.Variables[string(v)]; !ok; val, ok = gc.Variables[string(v)] {
  108. if gc.Parent == nil {
  109. return Error{fmt.Errorf("Could not evaluate variable: %s", string(v))}
  110. }
  111. gc = gc.Parent
  112. }
  113. return val
  114. }
  115. func (p *Parser) ParseVariable() Value {
  116. return p.ParseWhile(IsVariable, func(res string) Value {
  117. return Variable(res[1:len(res)]) // chop off the $
  118. })
  119. }
  120. type Number float32
  121. func (n Number) Eval(gc *GraphicContext) Value {
  122. return n
  123. }
  124. func (p *Parser) ParseWord() Value {
  125. return p.ParseWhile(IsWord, func(res string) Value {
  126. return Word(res)
  127. })
  128. }
  129. func (p *Parser) ParseNumber() Value {
  130. return p.ParseWhile(IsNumber, func(res string) Value {
  131. f, err := strconv.ParseFloat(res, 32)
  132. if err != nil {
  133. return p.Error("Cannot convert to number: %s, %s", res, err)
  134. }
  135. return Number(f)
  136. })
  137. }
  138. type Ref string
  139. func (r Ref) Eval(gc *GraphicContext) Value {
  140. var ok bool
  141. var val DefValue
  142. for val, ok = gc.Defs[string(r)]; !ok; val, ok = gc.Defs[string(r)] {
  143. if gc.Parent == nil {
  144. return Error{fmt.Errorf("Could not evaluate reference: %s", string(r))}
  145. }
  146. gc = gc.Parent
  147. }
  148. return val
  149. }
  150. type String string
  151. func (p Parser) IsString(r rune, i int) bool {
  152. if (i == 0) && (r == '"') {
  153. return true
  154. } else if r == '"' {
  155. return p.Buffer[p.Index+i-1] != '\\'
  156. } else {
  157. return true
  158. }
  159. }
  160. /*
  161. COMMANDS -> COMMAND COMMANDS | .
  162. COMMAND -> word PARAMS .
  163. PARAMS -> ws PARAM PARAMS | PARAM.
  164. PARAM -> LIST | ELEM | string | id | word | ref.
  165. LIST -> ELEM comma LIST | ELEM .
  166. ELEM -> var | number.
  167. Drawing Primitives
  168. Here is a complete description of the MVG drawing primitives:
  169. Primitive Description
  170. affine sx,rx,ry,sy,tx,ty
  171. arc x0,y0 x1,y1 a0,a1
  172. bezier x0,y0 ... xn,yn Bezier (spline) requires three or more x,y coordinates
  173. to define its shape. The first and last points are the knots
  174. (preserved coordinates) and any intermediate coordinates are the control points.
  175. If two control points are specified, the line between each end knot and its
  176. sequentially respective control point determines the tangent direction of the
  177. curve at that end. If one control point is specified, the lines from the end
  178. knots to the one control point determines the tangent directions of the curve
  179. at each end. If more than two control points are specified, then the
  180. additional control points act in combination to determine the intermediate
  181. shape of the curve. In order to draw complex curves, it is highly recommended
  182. either to use the Path primitive or to draw multiple four-point bezier segments
  183. with the start and end knots of each successive segment repeated.
  184. border-color color
  185. circle originx,originy perimeterx,perimetery
  186. clip-path url(name)
  187. clip-rule rule Choose from these rule types:
  188. evenodd
  189. nonzero
  190. clip-units units Choose from these unit types:
  191. userSpace
  192. userSpaceOnUse
  193. objectBoundingBox
  194. color x,y method Choose from these method types:
  195. point
  196. replace
  197. floodfill
  198. filltoborder
  199. reset
  200. compliance type Choose from these compliance types: MVG or SVG
  201. decorate type Choose from these types of decorations:
  202. none
  203. line-through
  204. overline
  205. underline
  206. ellipse centerx,centery radiusx,radiusy arcstart,arcstop
  207. fill color Choose from any of these colors.
  208. fill-opacity opacity The opacity ranges from 0.0 (fully transparent) to 1.0
  209. (fully opaque) or as a percentage (e.g. 50%).
  210. fill-rule rule Choose from these rule types:
  211. evenodd
  212. nonzero
  213. font name
  214. font-family family
  215. font-size point-size
  216. font-stretch type Choose from these stretch types:
  217. all
  218. normal
  219. ultra-condensed
  220. extra-condensed
  221. condensed
  222. semi-condensed
  223. semi-expanded
  224. expanded
  225. extra-expanded
  226. ultra-expanded
  227. font-style style Choose from these styles:
  228. all
  229. normal
  230. italic
  231. oblique
  232. font-weight weight Choose from these weights:
  233. all
  234. normal
  235. bold
  236. 100
  237. 200
  238. 300
  239. 400
  240. 500
  241. 600
  242. 700
  243. 800
  244. 900
  245. gradient-units units Choose from these units:
  246. userSpace
  247. userSpaceOnUse
  248. objectBoundingBox
  249. gravity type Choose from these gravity types:
  250. NorthWest
  251. North
  252. NorthEast
  253. West
  254. Center
  255. East
  256. SouthWest
  257. South
  258. SouthEast
  259. image compose x,y width,height 'filename' Choose from these compose operations:
  260. Method Description
  261. clear Both the color and the alpha of the destination are cleared. Neither the source nor the destination are used as input.
  262. src The source is copied to the destination. The destination is not used as input.
  263. dst The destination is left untouched.
  264. src-over The source is composited over the destination.
  265. dst-over The destination is composited over the source and the result replaces the destination.
  266. src-in The part of the source lying inside of the destination replaces the destination.
  267. dst-in The part of the destination lying inside of the source replaces the destination.
  268. src-out The part of the source lying outside of the destination replaces the destination.
  269. dst-out The part of the destination lying outside of the source replaces the destination.
  270. src-atop The part of the source lying inside of the destination is composited onto the destination.
  271. dst-atop The part of the destination lying inside of the source is composited over the source and replaces the destination.
  272. multiply The source is multiplied by the destination and replaces the destination. The resultant color is always at least as dark as either of the two constituent colors. Multiplying any color with black produces black. Multiplying any color with white leaves the original color unchanged.
  273. screen The source and destination are complemented and then multiplied and then replace the destination. The resultant color is always at least as light as either of the two constituent colors. Screening any color with white produces white. Screening any color with black leaves the original color unchanged.
  274. overlay Multiplies or screens the colors, dependent on the destination color. Source colors overlay the destination whilst preserving its highlights and shadows. The destination color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the destination.
  275. darken Selects the darker of the destination and source colors. The destination is replaced with the source when the source is darker, otherwise it is left unchanged.
  276. lighten Selects the lighter of the destination and source colors. The destination is replaced with the source when the source is lighter, otherwise it is left unchanged.
  277. linear-light Increase contrast slightly with an impact on the foreground's tonal values.
  278. color-dodge Brightens the destination color to reflect the source color. Painting with black produces no change.
  279. color-burn Darkens the destination color to reflect the source color. Painting with white produces no change.
  280. hard-light Multiplies or screens the colors, dependent on the source color value. If the source color is lighter than 0.5, the destination is lightened as if it were screened. If the source color is darker than 0.5, the destination is darkened, as if it were multiplied. The degree of lightening or darkening is proportional to the difference between the source color and 0.5. If it is equal to 0.5 the destination is unchanged. Painting with pure black or white produces black or white.
  281. soft-light Darkens or lightens the colors, dependent on the source color value. If the source color is lighter than 0.5, the destination is lightened. If the source color is darker than 0.5, the destination is darkened, as if it were burned in. The degree of darkening or lightening is proportional to the difference between the source color and 0.5. If it is equal to 0.5, the destination is unchanged. Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
  282. plus The source is added to the destination and replaces the destination. This operator is useful for animating a dissolve between two images.
  283. add As per 'plus' but transparency data is treated as matte values. As such any transparent areas in either image remain transparent.
  284. minus Subtract the colors in the source image from the destination image. When transparency is involved, Opaque areas will be subtracted from any destination opaque areas.
  285. subtract Subtract the colors in the source image from the destination image. When transparency is involved transparent areas are subtracted, so only the opaque areas in the source remain opaque in the destination image.
  286. difference Subtracts the darker of the two constituent colors from the lighter. Painting with white inverts the destination color. Painting with black produces no change.
  287. exclusion Produces an effect similar to that of 'difference', but appears as lower contrast. Painting with white inverts the destination color. Painting with black produces no change.
  288. xor The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source.
  289. copy-* Copy the specified channel in the source image to the same channel in the destination image. If the channel specified in the source image does not exist, (which can only happen for methods, 'copy-opacity' or 'copy-black') then it is assumed that the source image is a special grayscale channel image of the values to be copied.
  290. change-mask Replace any destination pixel that is the similar to the source images pixel (as defined by the current -fuzz factor), with transparency.
  291. interline-spacing pixels
  292. interword-spacing pixels
  293. kerning pixels
  294. line x,y x1,y1
  295. matte x,y method Choose from these methods:
  296. point
  297. replace
  298. floodfill
  299. filltoborder
  300. reset
  301. offset offset
  302. opacity opacity Use percent (e.g. 50%).
  303. path path
  304. point x,y
  305. polygon x,y x1,y1, ..., xn,yn
  306. polyline x,y x1,y1, ..., xn,yn
  307. pop clip-path
  308. pop defs
  309. pop gradient
  310. pop graphic-context
  311. pop pattern
  312. push clip-path "name"
  313. push defs
  314. push gradient id linear x,y x1,y1
  315. push gradient id radial xc,cy xf,yf radius
  316. push graphic-context { "id" } the id is optional
  317. push pattern id radial x,y width,height
  318. rectangle x,y x1,y1
  319. rotate angle
  320. roundrectangle x,y x1,y1 width,height
  321. scale x,y
  322. skewX angle
  323. skewX angle
  324. stop-color color offset
  325. stroke color
  326. stroke-antialias 0 • 1
  327. stroke-dasharray none • numeric-list
  328. stroke-dashoffset offset
  329. stroke-linecap type Choose from these cap types:
  330. butt
  331. round
  332. square
  333. stroke-linejoin type Choose from these join types:
  334. bevel
  335. miter
  336. round
  337. stroke-miterlimit limit
  338. stroke-opacity opacity The opacity ranges from 0.0 (fully transparent) to 1.0 (fully opaque) or as a percentage (e.g. 50%).
  339. stroke-width width
  340. text "text"
  341. text-antialias 0 • 1
  342. text-undercolor color
  343. translate x,y
  344. use "url(#id)"
  345. viewbox x,y x1,y1
  346. */