option.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. // Copyright (c) 2017 Ernest Micklei
  2. //
  3. // MIT License
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining
  6. // a copy of this software and associated documentation files (the
  7. // "Software"), to deal in the Software without restriction, including
  8. // without limitation the rights to use, copy, modify, merge, publish,
  9. // distribute, sublicense, and/or sell copies of the Software, and to
  10. // permit persons to whom the Software is furnished to do so, subject to
  11. // the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  20. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  21. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  22. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. package proto
  24. import (
  25. "bytes"
  26. "fmt"
  27. "sort"
  28. "text/scanner"
  29. )
  30. // Option is a protoc compiler option
  31. type Option struct {
  32. Position scanner.Position
  33. Comment *Comment
  34. Name string
  35. Constant Literal
  36. IsEmbedded bool
  37. // AggregatedConstants is DEPRECATED. These Literals are populated into Constant.OrderedMap
  38. AggregatedConstants []*NamedLiteral
  39. InlineComment *Comment
  40. Parent Visitee
  41. }
  42. // parse reads an Option body
  43. // ( ident | "(" fullIdent ")" ) { "." ident } "=" constant ";"
  44. func (o *Option) parse(p *Parser) error {
  45. pos, tok, lit := p.nextIdentifier()
  46. if tLEFTPAREN == tok {
  47. pos, tok, lit = p.nextIdentifier()
  48. if tok != tIDENT {
  49. if !isKeyword(tok) {
  50. return p.unexpected(lit, "option full identifier", o)
  51. }
  52. }
  53. pos, tok, _ = p.next()
  54. if tok != tRIGHTPAREN {
  55. return p.unexpected(lit, "option full identifier closing )", o)
  56. }
  57. o.Name = fmt.Sprintf("(%s)", lit)
  58. } else {
  59. // non full ident
  60. if tIDENT != tok {
  61. if !isKeyword(tok) {
  62. return p.unexpected(lit, "option identifier", o)
  63. }
  64. }
  65. o.Name = lit
  66. }
  67. pos, tok, lit = p.next()
  68. if tDOT == tok {
  69. // extend identifier
  70. pos, tok, lit = p.nextIdent(true) // keyword allowed as start
  71. if tok != tIDENT {
  72. if !isKeyword(tok) {
  73. return p.unexpected(lit, "option postfix identifier", o)
  74. }
  75. }
  76. o.Name = fmt.Sprintf("%s.%s", o.Name, lit)
  77. pos, tok, lit = p.next()
  78. }
  79. if tEQUALS != tok {
  80. return p.unexpected(lit, "option value assignment =", o)
  81. }
  82. r := p.peekNonWhitespace()
  83. var err error
  84. // values of an option can have illegal escape sequences
  85. // for the standard Go scanner used by this package.
  86. p.ignoreIllegalEscapesWhile(func() {
  87. if '{' == r {
  88. // aggregate
  89. p.next() // consume {
  90. err = o.parseAggregate(p)
  91. } else {
  92. // non aggregate
  93. l := new(Literal)
  94. l.Position = pos
  95. if e := l.parse(p); e != nil {
  96. err = e
  97. }
  98. o.Constant = *l
  99. }
  100. })
  101. return err
  102. }
  103. // inlineComment is part of commentInliner.
  104. func (o *Option) inlineComment(c *Comment) {
  105. o.InlineComment = c
  106. }
  107. // Accept dispatches the call to the visitor.
  108. func (o *Option) Accept(v Visitor) {
  109. v.VisitOption(o)
  110. }
  111. // Doc is part of Documented
  112. func (o *Option) Doc() *Comment {
  113. return o.Comment
  114. }
  115. // Literal represents intLit,floatLit,strLit or boolLit or a nested structure thereof.
  116. type Literal struct {
  117. Position scanner.Position
  118. Source string
  119. IsString bool
  120. // literal value can be an array literal value (even nested)
  121. Array []*Literal
  122. // literal value can be a map of literals (even nested)
  123. // DEPRECATED: use OrderedMap instead
  124. Map map[string]*Literal
  125. // literal value can be a map of literals (even nested)
  126. // this is done as pairs of name keys and literal values so the original ordering is preserved
  127. OrderedMap LiteralMap
  128. }
  129. // LiteralMap is like a map of *Literal but preserved the ordering.
  130. // Can be iterated yielding *NamedLiteral values.
  131. type LiteralMap []*NamedLiteral
  132. // Get returns a Literal from the map.
  133. func (m LiteralMap) Get(key string) (*Literal, bool) {
  134. for _, each := range m {
  135. if each.Name == key {
  136. // exit on the first match
  137. return each.Literal, true
  138. }
  139. }
  140. return new(Literal), false
  141. }
  142. // SourceRepresentation returns the source (if quoted then use double quote).
  143. func (l Literal) SourceRepresentation() string {
  144. var buf bytes.Buffer
  145. if l.IsString {
  146. buf.WriteRune('"')
  147. }
  148. buf.WriteString(l.Source)
  149. if l.IsString {
  150. buf.WriteRune('"')
  151. }
  152. return buf.String()
  153. }
  154. // parse expects to read a literal constant after =.
  155. func (l *Literal) parse(p *Parser) error {
  156. pos, tok, lit := p.next()
  157. if tok == tLEFTSQUARE {
  158. // collect array elements
  159. array := []*Literal{}
  160. for {
  161. e := new(Literal)
  162. if err := e.parse(p); err != nil {
  163. return err
  164. }
  165. array = append(array, e)
  166. _, tok, lit = p.next()
  167. if tok == tCOMMA {
  168. continue
  169. }
  170. if tok == tRIGHTSQUARE {
  171. break
  172. }
  173. return p.unexpected(lit, ", or ]", l)
  174. }
  175. l.Array = array
  176. l.IsString = false
  177. l.Position = pos
  178. return nil
  179. }
  180. if tLEFTCURLY == tok {
  181. l.Position, l.Source, l.IsString = pos, "", false
  182. constants, err := parseAggregateConstants(p, l)
  183. if err != nil {
  184. return nil
  185. }
  186. l.OrderedMap = LiteralMap(constants)
  187. return nil
  188. }
  189. if "-" == lit {
  190. // negative number
  191. if err := l.parse(p); err != nil {
  192. return err
  193. }
  194. // modify source and position
  195. l.Position, l.Source = pos, "-"+l.Source
  196. return nil
  197. }
  198. source := lit
  199. iss := isString(lit)
  200. if iss {
  201. source = unQuote(source)
  202. }
  203. l.Position, l.Source, l.IsString = pos, source, iss
  204. // peek for multiline strings
  205. for {
  206. pos, tok, lit = p.next()
  207. if isString(lit) {
  208. l.Source += unQuote(lit)
  209. } else {
  210. p.nextPut(pos, tok, lit)
  211. break
  212. }
  213. }
  214. return nil
  215. }
  216. // NamedLiteral associates a name with a Literal
  217. type NamedLiteral struct {
  218. *Literal
  219. Name string
  220. // PrintsColon is true when the Name must be printed with a colon suffix
  221. PrintsColon bool
  222. }
  223. // parseAggregate reads options written using aggregate syntax.
  224. // tLEFTCURLY { has been consumed
  225. func (o *Option) parseAggregate(p *Parser) error {
  226. constants, err := parseAggregateConstants(p, o)
  227. literalMap := map[string]*Literal{}
  228. for _, each := range constants {
  229. literalMap[each.Name] = each.Literal
  230. }
  231. o.Constant = Literal{Map: literalMap, OrderedMap: constants, Position: o.Position}
  232. // reconstruct the old, deprecated field
  233. o.AggregatedConstants = collectAggregatedConstants(literalMap)
  234. return err
  235. }
  236. // flatten the maps of each literal, recursively
  237. // this func exists for deprecated Option.AggregatedConstants.
  238. func collectAggregatedConstants(m map[string]*Literal) (list []*NamedLiteral) {
  239. for k, v := range m {
  240. if v.Map != nil {
  241. sublist := collectAggregatedConstants(v.Map)
  242. for _, each := range sublist {
  243. list = append(list, &NamedLiteral{
  244. Name: k + "." + each.Name,
  245. PrintsColon: true,
  246. Literal: each.Literal,
  247. })
  248. }
  249. } else {
  250. list = append(list, &NamedLiteral{
  251. Name: k,
  252. PrintsColon: true,
  253. Literal: v,
  254. })
  255. }
  256. }
  257. // sort list by position of literal
  258. sort.Sort(byPosition(list))
  259. return
  260. }
  261. type byPosition []*NamedLiteral
  262. func (b byPosition) Less(i, j int) bool {
  263. return b[i].Literal.Position.Line < b[j].Literal.Position.Line
  264. }
  265. func (b byPosition) Len() int { return len(b) }
  266. func (b byPosition) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
  267. func parseAggregateConstants(p *Parser, container interface{}) (list []*NamedLiteral, err error) {
  268. for {
  269. pos, tok, lit := p.nextIdentifier()
  270. if tRIGHTSQUARE == tok {
  271. p.nextPut(pos, tok, lit)
  272. // caller has checked for open square ; will consume rightsquare, rightcurly and semicolon
  273. return
  274. }
  275. if tRIGHTCURLY == tok {
  276. return
  277. }
  278. if tSEMICOLON == tok {
  279. // just consume it
  280. continue
  281. //return
  282. }
  283. if tCOMMENT == tok {
  284. // assign to last parsed literal
  285. // TODO: see TestUseOfSemicolonsInAggregatedConstants
  286. continue
  287. }
  288. if tCOMMA == tok {
  289. if len(list) == 0 {
  290. err = p.unexpected(lit, "non-empty option aggregate key", container)
  291. return
  292. }
  293. continue
  294. }
  295. if tIDENT != tok && !isKeyword(tok) {
  296. err = p.unexpected(lit, "option aggregate key", container)
  297. return
  298. }
  299. // workaround issue #59 TODO
  300. if isString(lit) && len(list) > 0 {
  301. // concatenate with previous constant
  302. list[len(list)-1].Source += unQuote(lit)
  303. continue
  304. }
  305. key := lit
  306. printsColon := false
  307. // expect colon, aggregate or plain literal
  308. pos, tok, lit = p.next()
  309. if tCOLON == tok {
  310. // consume it
  311. printsColon = true
  312. pos, tok, lit = p.next()
  313. }
  314. // see if nested aggregate is started
  315. if tLEFTCURLY == tok {
  316. nested, fault := parseAggregateConstants(p, container)
  317. if fault != nil {
  318. err = fault
  319. return
  320. }
  321. // create the map
  322. m := map[string]*Literal{}
  323. for _, each := range nested {
  324. m[each.Name] = each.Literal
  325. }
  326. list = append(list, &NamedLiteral{
  327. Name: key,
  328. PrintsColon: printsColon,
  329. Literal: &Literal{Map: m, OrderedMap: LiteralMap(nested)}})
  330. continue
  331. }
  332. // no aggregate, put back token
  333. p.nextPut(pos, tok, lit)
  334. // now we see plain literal
  335. l := new(Literal)
  336. l.Position = pos
  337. if err = l.parse(p); err != nil {
  338. return
  339. }
  340. list = append(list, &NamedLiteral{Name: key, Literal: l, PrintsColon: printsColon})
  341. }
  342. }
  343. func (o *Option) parent(v Visitee) { o.Parent = v }