Nessuna descrizione

demangle.go 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package demangle defines functions that demangle GCC/LLVM C++ symbol names.
  5. // This package recognizes names that were mangled according to the C++ ABI
  6. // defined at http://codesourcery.com/cxx-abi/.
  7. package demangle
  8. import (
  9. "errors"
  10. "fmt"
  11. "strings"
  12. )
  13. // ErrNotMangledName is returned by CheckedDemangle if the string does
  14. // not appear to be a C++ symbol name.
  15. var ErrNotMangledName = errors.New("not a C++ mangled name")
  16. // Option is the type of demangler options.
  17. type Option int
  18. const (
  19. // The NoParams option disables demangling of function parameters.
  20. NoParams Option = iota
  21. // The NoTemplateParams option disables demangling of template parameters.
  22. NoTemplateParams
  23. // The NoClones option disables inclusion of clone suffixes.
  24. // NoParams implies NoClones.
  25. NoClones
  26. // The Verbose option turns on more verbose demangling.
  27. Verbose
  28. )
  29. // Filter demangles a C++ symbol name, returning the human-readable C++ name.
  30. // If any error occurs during demangling, the input string is returned.
  31. func Filter(name string, options ...Option) string {
  32. ret, err := ToString(name, options...)
  33. if err != nil {
  34. return name
  35. }
  36. return ret
  37. }
  38. // ToString demangles a C++ symbol name, returning human-readable C++
  39. // name or an error.
  40. // If the name does not appear to be a C++ symbol name at all, the
  41. // error will be ErrNotMangledName.
  42. func ToString(name string, options ...Option) (string, error) {
  43. a, err := ToAST(name, options...)
  44. if err != nil {
  45. return "", err
  46. }
  47. return ASTToString(a, options...), nil
  48. }
  49. // ToAST demangles a C++ symbol name into an abstract syntax tree
  50. // representing the symbol.
  51. // If the NoParams option is passed, and the name has a function type,
  52. // the parameter types are not demangled.
  53. // If the name does not appear to be a C++ symbol name at all, the
  54. // error will be ErrNotMangledName.
  55. func ToAST(name string, options ...Option) (AST, error) {
  56. if strings.HasPrefix(name, "_Z") {
  57. a, err := doDemangle(name[2:], options...)
  58. return a, adjustErr(err, 2)
  59. }
  60. const prefix = "_GLOBAL_"
  61. if strings.HasPrefix(name, prefix) {
  62. // The standard demangler ignores NoParams for global
  63. // constructors. We are compatible.
  64. i := 0
  65. for i < len(options) {
  66. if options[i] == NoParams {
  67. options = append(options[:i], options[i+1:]...)
  68. } else {
  69. i++
  70. }
  71. }
  72. a, err := globalCDtorName(name[len(prefix):], options...)
  73. return a, adjustErr(err, len(prefix))
  74. }
  75. return nil, ErrNotMangledName
  76. }
  77. // globalCDtorName demangles a global constructor/destructor symbol name.
  78. // The parameter is the string following the "_GLOBAL_" prefix.
  79. func globalCDtorName(name string, options ...Option) (AST, error) {
  80. if len(name) < 4 {
  81. return nil, ErrNotMangledName
  82. }
  83. switch name[0] {
  84. case '.', '_', '$':
  85. default:
  86. return nil, ErrNotMangledName
  87. }
  88. var ctor bool
  89. switch name[1] {
  90. case 'I':
  91. ctor = true
  92. case 'D':
  93. ctor = false
  94. default:
  95. return nil, ErrNotMangledName
  96. }
  97. if name[2] != '_' {
  98. return nil, ErrNotMangledName
  99. }
  100. if !strings.HasPrefix(name[3:], "_Z") {
  101. return &GlobalCDtor{Ctor: ctor, Key: &Name{Name: name}}, nil
  102. } else {
  103. a, err := doDemangle(name[5:], options...)
  104. if err != nil {
  105. return nil, adjustErr(err, 5)
  106. }
  107. return &GlobalCDtor{Ctor: ctor, Key: a}, nil
  108. }
  109. }
  110. // The doDemangle function is the entry point into the demangler proper.
  111. func doDemangle(name string, options ...Option) (ret AST, err error) {
  112. // When the demangling routines encounter an error, they panic
  113. // with a value of type demangleErr.
  114. defer func() {
  115. if r := recover(); r != nil {
  116. if de, ok := r.(demangleErr); ok {
  117. ret = nil
  118. err = de
  119. return
  120. }
  121. panic(r)
  122. }
  123. }()
  124. params := true
  125. clones := true
  126. verbose := false
  127. for _, o := range options {
  128. switch o {
  129. case NoParams:
  130. params = false
  131. clones = false
  132. case NoTemplateParams:
  133. // This is a valid option but only affect printing of the AST.
  134. case NoClones:
  135. clones = false
  136. case Verbose:
  137. verbose = true
  138. default:
  139. return nil, fmt.Errorf("unrecognized demangler option %v", o)
  140. }
  141. }
  142. st := &state{str: name, verbose: verbose}
  143. a := st.encoding(params)
  144. // Accept a clone suffix.
  145. if clones {
  146. for len(st.str) > 1 && st.str[0] == '.' && (isLower(st.str[1]) || st.str[1] == '_' || isDigit(st.str[1])) {
  147. a = st.cloneSuffix(a)
  148. }
  149. }
  150. if clones && len(st.str) > 0 {
  151. st.fail("unparsed characters at end of mangled name")
  152. }
  153. return a, nil
  154. }
  155. // A state holds the current state of demangling a string.
  156. type state struct {
  157. str string // remainder of string to demangle
  158. verbose bool // whether to use verbose demangling
  159. off int // offset of str within original string
  160. subs substitutions // substitutions
  161. templates []*Template // templates being processed
  162. }
  163. // copy returns a copy of the current state.
  164. func (st *state) copy() *state {
  165. n := new(state)
  166. *n = *st
  167. return n
  168. }
  169. // fail panics with demangleErr, to be caught in doDemangle.
  170. func (st *state) fail(err string) {
  171. panic(demangleErr{err: err, off: st.off})
  172. }
  173. // failEarlier is like fail, but decrements the offset to indicate
  174. // that the point of failure occurred earlier in the string.
  175. func (st *state) failEarlier(err string, dec int) {
  176. if st.off < dec {
  177. panic("internal error")
  178. }
  179. panic(demangleErr{err: err, off: st.off - dec})
  180. }
  181. // advance advances the current string offset.
  182. func (st *state) advance(add int) {
  183. if len(st.str) < add {
  184. panic("internal error")
  185. }
  186. st.str = st.str[add:]
  187. st.off += add
  188. }
  189. // checkChar requires that the next character in the string be c, and
  190. // advances past it.
  191. func (st *state) checkChar(c byte) {
  192. if len(st.str) == 0 || st.str[0] != c {
  193. panic("internal error")
  194. }
  195. st.advance(1)
  196. }
  197. // A demangleErr is an error at a specific offset in the mangled
  198. // string.
  199. type demangleErr struct {
  200. err string
  201. off int
  202. }
  203. // Error implements the builtin error interface for demangleErr.
  204. func (de demangleErr) Error() string {
  205. return fmt.Sprintf("%s at %d", de.err, de.off)
  206. }
  207. // adjustErr adjusts the position of err, if it is a demangleErr,
  208. // and returns err.
  209. func adjustErr(err error, adj int) error {
  210. if err == nil {
  211. return nil
  212. }
  213. if de, ok := err.(demangleErr); ok {
  214. de.off += adj
  215. return de
  216. }
  217. return err
  218. }
  219. // encoding ::= <(function) name> <bare-function-type>
  220. // <(data) name>
  221. // <special-name>
  222. func (st *state) encoding(params bool) AST {
  223. if len(st.str) < 1 {
  224. st.fail("expected encoding")
  225. }
  226. if st.str[0] == 'G' || st.str[0] == 'T' {
  227. return st.specialName()
  228. }
  229. a := st.name()
  230. a = simplify(a)
  231. if !params {
  232. // Don't demangle the parameters.
  233. // Strip CV-qualifiers, as they apply to the 'this'
  234. // parameter, and are not output by the standard
  235. // demangler without parameters.
  236. if mwq, ok := a.(*MethodWithQualifiers); ok {
  237. a = mwq.Method
  238. }
  239. // If this is a local name, there may be CV-qualifiers
  240. // on the name that really apply to the top level, and
  241. // therefore must be discarded when discarding
  242. // parameters. This can happen when parsing a class
  243. // that is local to a function.
  244. if q, ok := a.(*Qualified); ok && q.LocalName {
  245. p := &q.Name
  246. if da, ok := (*p).(*DefaultArg); ok {
  247. p = &da.Arg
  248. }
  249. if mwq, ok := (*p).(*MethodWithQualifiers); ok {
  250. *p = mwq.Method
  251. }
  252. }
  253. return a
  254. }
  255. if len(st.str) == 0 || st.str[0] == 'E' {
  256. // There are no parameters--this is a data symbol, not
  257. // a function symbol.
  258. return a
  259. }
  260. check := a
  261. mwq, _ := check.(*MethodWithQualifiers)
  262. if mwq != nil {
  263. check = mwq.Method
  264. }
  265. template, _ := check.(*Template)
  266. if template != nil {
  267. st.templates = append(st.templates, template)
  268. }
  269. ft := st.bareFunctionType(hasReturnType(a))
  270. if template != nil {
  271. st.templates = st.templates[:len(st.templates)-1]
  272. }
  273. ft = simplify(ft)
  274. // Any top-level qualifiers belong to the function type.
  275. if mwq != nil {
  276. a = mwq.Method
  277. mwq.Method = ft
  278. ft = mwq
  279. }
  280. if q, ok := a.(*Qualified); ok && q.LocalName {
  281. p := &q.Name
  282. if da, ok := (*p).(*DefaultArg); ok {
  283. p = &da.Arg
  284. }
  285. if mwq, ok := (*p).(*MethodWithQualifiers); ok {
  286. *p = mwq.Method
  287. mwq.Method = ft
  288. ft = mwq
  289. }
  290. }
  291. return &Typed{Name: a, Type: ft}
  292. }
  293. // hasReturnType returns whether the mangled form of a will have a
  294. // return type.
  295. func hasReturnType(a AST) bool {
  296. switch a := a.(type) {
  297. case *Template:
  298. return !isCDtorConversion(a.Name)
  299. case *TypeWithQualifiers:
  300. return hasReturnType(a.Base)
  301. case *MethodWithQualifiers:
  302. return hasReturnType(a.Method)
  303. default:
  304. return false
  305. }
  306. }
  307. // isCDtorConversion returns when an AST is a constructor, a
  308. // destructor, or a conversion operator.
  309. func isCDtorConversion(a AST) bool {
  310. switch a := a.(type) {
  311. case *Qualified:
  312. return isCDtorConversion(a.Name)
  313. case *Constructor, *Destructor, *Cast:
  314. return true
  315. default:
  316. return false
  317. }
  318. }
  319. // <tagged-name> ::= <name> B <source-name>
  320. func (st *state) taggedName(a AST) AST {
  321. for len(st.str) > 0 && st.str[0] == 'B' {
  322. st.advance(1)
  323. tag := st.sourceName()
  324. a = &TaggedName{Name: a, Tag: tag}
  325. }
  326. return a
  327. }
  328. // <name> ::= <nested-name>
  329. // ::= <unscoped-name>
  330. // ::= <unscoped-template-name> <template-args>
  331. // ::= <local-name>
  332. //
  333. // <unscoped-name> ::= <unqualified-name>
  334. // ::= St <unqualified-name>
  335. //
  336. // <unscoped-template-name> ::= <unscoped-name>
  337. // ::= <substitution>
  338. func (st *state) name() AST {
  339. if len(st.str) < 1 {
  340. st.fail("expected name")
  341. }
  342. switch st.str[0] {
  343. case 'N':
  344. return st.nestedName()
  345. case 'Z':
  346. return st.localName()
  347. case 'U':
  348. return st.unqualifiedName()
  349. case 'S':
  350. if len(st.str) < 2 {
  351. st.advance(1)
  352. st.fail("expected substitution index")
  353. }
  354. var a AST
  355. subst := false
  356. if st.str[1] == 't' {
  357. st.advance(2)
  358. a = st.unqualifiedName()
  359. a = &Qualified{Scope: &Name{Name: "std"}, Name: a, LocalName: false}
  360. } else {
  361. a = st.substitution(false)
  362. subst = true
  363. }
  364. if len(st.str) > 0 && st.str[0] == 'I' {
  365. // This can only happen if we saw
  366. // <unscoped-template-name> and are about to see
  367. // <template-args>. <unscoped-template-name> is a
  368. // substitution candidate if it did not come from a
  369. // substitution.
  370. if !subst {
  371. st.subs.add(a)
  372. }
  373. args := st.templateArgs()
  374. a = &Template{Name: a, Args: args}
  375. }
  376. return a
  377. default:
  378. a := st.unqualifiedName()
  379. if len(st.str) > 0 && st.str[0] == 'I' {
  380. st.subs.add(a)
  381. args := st.templateArgs()
  382. a = &Template{Name: a, Args: args}
  383. }
  384. return a
  385. }
  386. }
  387. // <nested-name> ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
  388. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> <template-args> E
  389. func (st *state) nestedName() AST {
  390. st.checkChar('N')
  391. q := st.cvQualifiers()
  392. r := st.refQualifier()
  393. a := st.prefix()
  394. if len(q) > 0 || r != "" {
  395. a = &MethodWithQualifiers{Method: a, Qualifiers: q, RefQualifier: r}
  396. }
  397. if len(st.str) == 0 || st.str[0] != 'E' {
  398. st.fail("expected E after nested name")
  399. }
  400. st.advance(1)
  401. return a
  402. }
  403. // <prefix> ::= <prefix> <unqualified-name>
  404. // ::= <template-prefix> <template-args>
  405. // ::= <template-param>
  406. // ::= <decltype>
  407. // ::=
  408. // ::= <substitution>
  409. //
  410. // <template-prefix> ::= <prefix> <(template) unqualified-name>
  411. // ::= <template-param>
  412. // ::= <substitution>
  413. //
  414. // <decltype> ::= Dt <expression> E
  415. // ::= DT <expression> E
  416. func (st *state) prefix() AST {
  417. var a AST
  418. // The last name seen, for a constructor/destructor.
  419. var last AST
  420. getLast := func(a AST) AST {
  421. for {
  422. if t, ok := a.(*Template); ok {
  423. a = t.Name
  424. } else if q, ok := a.(*Qualified); ok {
  425. a = q.Name
  426. } else if t, ok := a.(*TaggedName); ok {
  427. a = t.Name
  428. } else {
  429. return a
  430. }
  431. }
  432. }
  433. isCast := false
  434. for {
  435. if len(st.str) == 0 {
  436. st.fail("expected prefix")
  437. }
  438. var next AST
  439. c := st.str[0]
  440. if isDigit(c) || isLower(c) || c == 'U' || c == 'L' {
  441. next = st.unqualifiedName()
  442. if _, ok := next.(*Cast); ok {
  443. isCast = true
  444. }
  445. } else {
  446. switch st.str[0] {
  447. case 'C':
  448. if len(st.str) < 2 {
  449. st.fail("expected constructor type")
  450. }
  451. if last == nil {
  452. st.fail("constructor before name is seen")
  453. }
  454. st.advance(2)
  455. next = &Constructor{Name: getLast(last)}
  456. case 'D':
  457. if len(st.str) > 1 && (st.str[1] == 'T' || st.str[1] == 't') {
  458. next = st.demangleType(false)
  459. } else {
  460. if len(st.str) < 2 {
  461. st.fail("expected destructor type")
  462. }
  463. if last == nil {
  464. st.fail("destructor before name is seen")
  465. }
  466. st.advance(2)
  467. next = &Destructor{Name: getLast(last)}
  468. }
  469. case 'S':
  470. next = st.substitution(true)
  471. case 'I':
  472. if a == nil {
  473. st.fail("unexpected template arguments")
  474. }
  475. var args []AST
  476. args = st.templateArgs()
  477. tmpl := &Template{Name: a, Args: args}
  478. if isCast {
  479. st.setTemplate(a, tmpl)
  480. isCast = false
  481. }
  482. a = nil
  483. next = tmpl
  484. case 'T':
  485. next = st.templateParam()
  486. case 'E':
  487. return a
  488. case 'M':
  489. if a == nil {
  490. st.fail("unexpected lambda initializer")
  491. }
  492. // This is the initializer scope for a
  493. // lambda. We don't need to record
  494. // it. The normal code will treat the
  495. // variable has a type scope, which
  496. // gives appropriate output.
  497. st.advance(1)
  498. continue
  499. default:
  500. st.fail("unrecognized letter in prefix")
  501. }
  502. }
  503. last = next
  504. if a == nil {
  505. a = next
  506. } else {
  507. a = &Qualified{Scope: a, Name: next, LocalName: false}
  508. }
  509. if c != 'S' && (len(st.str) == 0 || st.str[0] != 'E') {
  510. st.subs.add(a)
  511. }
  512. }
  513. }
  514. // <unqualified-name> ::= <operator-name>
  515. // ::= <ctor-dtor-name>
  516. // ::= <source-name>
  517. // ::= <local-source-name>
  518. //
  519. // <local-source-name> ::= L <source-name> <discriminator>
  520. func (st *state) unqualifiedName() AST {
  521. if len(st.str) < 1 {
  522. st.fail("expected unqualified name")
  523. }
  524. var a AST
  525. c := st.str[0]
  526. if isDigit(c) {
  527. a = st.sourceName()
  528. } else if isLower(c) {
  529. a, _ = st.operatorName(false)
  530. if op, ok := a.(*Operator); ok && op.Name == `operator"" ` {
  531. n := st.sourceName()
  532. a = &Unary{Op: op, Expr: n, Suffix: false, SizeofType: false}
  533. }
  534. } else {
  535. switch c {
  536. case 'C', 'D':
  537. st.fail("constructor/destructor not in nested name")
  538. case 'L':
  539. st.advance(1)
  540. a = st.sourceName()
  541. a = st.discriminator(a)
  542. case 'U':
  543. if len(st.str) < 2 {
  544. st.advance(1)
  545. st.fail("expected closure or unnamed type")
  546. }
  547. c := st.str[1]
  548. switch c {
  549. case 'l':
  550. a = st.closureTypeName()
  551. case 't':
  552. a = st.unnamedTypeName()
  553. default:
  554. st.advance(1)
  555. st.fail("expected closure or unnamed type")
  556. }
  557. default:
  558. st.fail("expected unqualified name")
  559. }
  560. }
  561. if len(st.str) > 0 && st.str[0] == 'B' {
  562. a = st.taggedName(a)
  563. }
  564. return a
  565. }
  566. // <source-name> ::= <(positive length) number> <identifier>
  567. // identifier ::= <(unqualified source code identifier)>
  568. func (st *state) sourceName() AST {
  569. val := st.number()
  570. if val < 0 {
  571. st.fail("unexpected negative number")
  572. }
  573. if len(st.str) < val {
  574. st.fail("not enough characters for identifier")
  575. }
  576. id := st.str[:val]
  577. st.advance(val)
  578. // Look for GCC encoding of anonymous namespace, and make it
  579. // more friendly.
  580. const anonPrefix = "_GLOBAL_"
  581. if strings.HasPrefix(id, anonPrefix) && len(id) > len(anonPrefix)+2 {
  582. c1 := id[len(anonPrefix)]
  583. c2 := id[len(anonPrefix)+1]
  584. if (c1 == '.' || c1 == '_' || c1 == '$') && c2 == 'N' {
  585. id = "(anonymous namespace)"
  586. }
  587. }
  588. n := &Name{Name: id}
  589. return n
  590. }
  591. // number ::= [n] <(non-negative decimal integer)>
  592. func (st *state) number() int {
  593. neg := false
  594. if len(st.str) > 0 && st.str[0] == 'n' {
  595. neg = true
  596. st.advance(1)
  597. }
  598. if len(st.str) == 0 || !isDigit(st.str[0]) {
  599. st.fail("missing number")
  600. }
  601. val := 0
  602. for len(st.str) > 0 && isDigit(st.str[0]) {
  603. // Number picked to ensure we can't overflow with 32-bit int.
  604. // Any very large number here is bogus.
  605. if val >= 0x80000000/10-10 {
  606. st.fail("numeric overflow")
  607. }
  608. val = val*10 + int(st.str[0]-'0')
  609. st.advance(1)
  610. }
  611. if neg {
  612. val = -val
  613. }
  614. return val
  615. }
  616. // An operator is the demangled name, and the number of arguments it
  617. // takes in an expression.
  618. type operator struct {
  619. name string
  620. args int
  621. }
  622. // The operators map maps the mangled operator names to information
  623. // about them.
  624. var operators = map[string]operator{
  625. "aN": {"&=", 2},
  626. "aS": {"=", 2},
  627. "aa": {"&&", 2},
  628. "ad": {"&", 1},
  629. "an": {"&", 2},
  630. "at": {"alignof ", 1},
  631. "az": {"alignof ", 1},
  632. "cc": {"const_cast", 2},
  633. "cl": {"()", 2},
  634. "cm": {",", 2},
  635. "co": {"~", 1},
  636. "dV": {"/=", 2},
  637. "da": {"delete[] ", 1},
  638. "dc": {"dynamic_cast", 2},
  639. "de": {"*", 1},
  640. "dl": {"delete ", 1},
  641. "ds": {".*", 2},
  642. "dt": {".", 2},
  643. "dv": {"/", 2},
  644. "eO": {"^=", 2},
  645. "eo": {"^", 2},
  646. "eq": {"==", 2},
  647. "ge": {">=", 2},
  648. "gs": {"::", 1},
  649. "gt": {">", 2},
  650. "ix": {"[]", 2},
  651. "lS": {"<<=", 2},
  652. "le": {"<=", 2},
  653. "li": {`operator"" `, 1},
  654. "ls": {"<<", 2},
  655. "lt": {"<", 2},
  656. "mI": {"-=", 2},
  657. "mL": {"*=", 2},
  658. "mi": {"-", 2},
  659. "ml": {"*", 2},
  660. "mm": {"--", 1},
  661. "na": {"new[]", 3},
  662. "ne": {"!=", 2},
  663. "ng": {"-", 1},
  664. "nt": {"!", 1},
  665. "nw": {"new", 3},
  666. "oR": {"|=", 2},
  667. "oo": {"||", 2},
  668. "or": {"|", 2},
  669. "pL": {"+=", 2},
  670. "pl": {"+", 2},
  671. "pm": {"->*", 2},
  672. "pp": {"++", 1},
  673. "ps": {"+", 1},
  674. "pt": {"->", 2},
  675. "qu": {"?", 3},
  676. "rM": {"%=", 2},
  677. "rS": {">>=", 2},
  678. "rc": {"reinterpret_cast", 2},
  679. "rm": {"%", 2},
  680. "rs": {">>", 2},
  681. "sc": {"static_cast", 2},
  682. "st": {"sizeof ", 1},
  683. "sz": {"sizeof ", 1},
  684. "tr": {"throw", 0},
  685. "tw": {"throw ", 1},
  686. }
  687. // operator_name ::= many different two character encodings.
  688. // ::= cv <type>
  689. // ::= v <digit> <source-name>
  690. //
  691. // We need to know whether we are in an expression because it affects
  692. // how we handle template parameters in the type of a cast operator.
  693. func (st *state) operatorName(inExpression bool) (AST, int) {
  694. if len(st.str) < 2 {
  695. st.fail("missing operator code")
  696. }
  697. code := st.str[:2]
  698. st.advance(2)
  699. if code[0] == 'v' && isDigit(code[1]) {
  700. name := st.sourceName()
  701. return &Operator{Name: name.(*Name).Name}, int(code[1] - '0')
  702. } else if code == "cv" {
  703. // Push a nil on templates to indicate that template
  704. // parameters will have their template filled in
  705. // later.
  706. if !inExpression {
  707. st.templates = append(st.templates, nil)
  708. }
  709. t := st.demangleType(!inExpression)
  710. if !inExpression {
  711. st.templates = st.templates[:len(st.templates)-1]
  712. }
  713. return &Cast{To: t}, 1
  714. } else if op, ok := operators[code]; ok {
  715. return &Operator{Name: op.name}, op.args
  716. } else {
  717. st.failEarlier("unrecognized operator code", 2)
  718. panic("not reached")
  719. }
  720. }
  721. // <local-name> ::= Z <(function) encoding> E <(entity) name> [<discriminator>]
  722. // ::= Z <(function) encoding> E s [<discriminator>]
  723. // ::= Z <(function) encoding> E d [<parameter> number>] _ <entity name>
  724. func (st *state) localName() AST {
  725. st.checkChar('Z')
  726. fn := st.encoding(true)
  727. if len(st.str) == 0 || st.str[0] != 'E' {
  728. st.fail("expected E after local name")
  729. }
  730. st.advance(1)
  731. if len(st.str) > 0 && st.str[0] == 's' {
  732. st.advance(1)
  733. var n AST = &Name{Name: "string literal"}
  734. n = st.discriminator(n)
  735. return &Qualified{Scope: fn, Name: n, LocalName: true}
  736. } else {
  737. num := -1
  738. if len(st.str) > 0 && st.str[0] == 'd' {
  739. // Default argument scope.
  740. st.advance(1)
  741. num = st.compactNumber()
  742. }
  743. var n AST = st.name()
  744. n = st.discriminator(n)
  745. if num >= 0 {
  746. n = &DefaultArg{Num: num, Arg: n}
  747. }
  748. return &Qualified{Scope: fn, Name: n, LocalName: true}
  749. }
  750. }
  751. // Parse a Java resource special-name.
  752. func (st *state) javaResource() AST {
  753. off := st.off
  754. ln := st.number()
  755. if ln <= 1 {
  756. st.failEarlier("java resource length less than 1", st.off-off)
  757. }
  758. if len(st.str) == 0 || st.str[0] != '_' {
  759. st.fail("expected _ after number")
  760. }
  761. st.advance(1)
  762. ln--
  763. if len(st.str) < ln {
  764. st.fail("not enough characters for java resource length")
  765. }
  766. str := st.str[:ln]
  767. final := ""
  768. st.advance(ln)
  769. for i := 0; i < len(str); i++ {
  770. if str[i] != '$' {
  771. final += string(str[i])
  772. } else {
  773. if len(str) <= i+1 {
  774. st.failEarlier("java resource escape at end of string", 1)
  775. }
  776. i++
  777. r, ok := map[byte]string{
  778. 'S': "/",
  779. '_': ".",
  780. '$': "$",
  781. }[str[i]]
  782. if !ok {
  783. st.failEarlier("unrecognized java resource escape", ln-i-1)
  784. }
  785. final += r
  786. }
  787. }
  788. return &Special{Prefix: "java resource ", Val: &Name{Name: final}}
  789. }
  790. // <special-name> ::= TV <type>
  791. // ::= TT <type>
  792. // ::= TI <type>
  793. // ::= TS <type>
  794. // ::= GV <(object) name>
  795. // ::= T <call-offset> <(base) encoding>
  796. // ::= Tc <call-offset> <call-offset> <(base) encoding>
  797. // Also g++ extensions:
  798. // ::= TC <type> <(offset) number> _ <(base) type>
  799. // ::= TF <type>
  800. // ::= TJ <type>
  801. // ::= GR <name>
  802. // ::= GA <encoding>
  803. // ::= Gr <resource name>
  804. // ::= GTt <encoding>
  805. // ::= GTn <encoding>
  806. func (st *state) specialName() AST {
  807. if st.str[0] == 'T' {
  808. st.advance(1)
  809. if len(st.str) == 0 {
  810. st.fail("expected special name code")
  811. }
  812. c := st.str[0]
  813. st.advance(1)
  814. switch c {
  815. case 'V':
  816. t := st.demangleType(false)
  817. return &Special{Prefix: "vtable for ", Val: t}
  818. case 'T':
  819. t := st.demangleType(false)
  820. return &Special{Prefix: "VTT for ", Val: t}
  821. case 'I':
  822. t := st.demangleType(false)
  823. return &Special{Prefix: "typeinfo for ", Val: t}
  824. case 'S':
  825. t := st.demangleType(false)
  826. return &Special{Prefix: "typeinfo name for ", Val: t}
  827. case 'h':
  828. st.callOffset('h')
  829. v := st.encoding(true)
  830. return &Special{Prefix: "non-virtual thunk to ", Val: v}
  831. case 'v':
  832. st.callOffset('v')
  833. v := st.encoding(true)
  834. return &Special{Prefix: "virtual thunk to ", Val: v}
  835. case 'c':
  836. st.callOffset(0)
  837. st.callOffset(0)
  838. v := st.encoding(true)
  839. return &Special{Prefix: "covariant return thunk to ", Val: v}
  840. case 'C':
  841. derived := st.demangleType(false)
  842. off := st.off
  843. offset := st.number()
  844. if offset < 0 {
  845. st.failEarlier("expected positive offset", st.off-off)
  846. }
  847. if len(st.str) == 0 || st.str[0] != '_' {
  848. st.fail("expected _ after number")
  849. }
  850. st.advance(1)
  851. base := st.demangleType(false)
  852. return &Special2{Prefix: "construction vtable for ", Val1: base, Middle: "-in-", Val2: derived}
  853. case 'F':
  854. t := st.demangleType(false)
  855. return &Special{Prefix: "typeinfo fn for ", Val: t}
  856. case 'J':
  857. t := st.demangleType(false)
  858. return &Special{Prefix: "java Class for ", Val: t}
  859. case 'H':
  860. n := st.name()
  861. return &Special{Prefix: "TLS init function for ", Val: n}
  862. case 'W':
  863. n := st.name()
  864. return &Special{Prefix: "TLS wrapper function for ", Val: n}
  865. default:
  866. st.fail("unrecognized special T name code")
  867. panic("not reached")
  868. }
  869. } else {
  870. st.checkChar('G')
  871. if len(st.str) == 0 {
  872. st.fail("expected special name code")
  873. }
  874. c := st.str[0]
  875. st.advance(1)
  876. switch c {
  877. case 'V':
  878. n := st.name()
  879. return &Special{Prefix: "guard variable for ", Val: n}
  880. case 'R':
  881. n := st.name()
  882. i := st.number()
  883. return &Special{Prefix: fmt.Sprintf("reference temporary #%d for ", i), Val: n}
  884. case 'A':
  885. v := st.encoding(true)
  886. return &Special{Prefix: "hidden alias for ", Val: v}
  887. case 'T':
  888. if len(st.str) == 0 {
  889. st.fail("expected special GT name code")
  890. }
  891. c := st.str[0]
  892. st.advance(1)
  893. v := st.encoding(true)
  894. switch c {
  895. case 'n':
  896. return &Special{Prefix: "non-transaction clone for ", Val: v}
  897. default:
  898. // The proposal is that different
  899. // letters stand for different types
  900. // of transactional cloning. Treat
  901. // them all the same for now.
  902. fallthrough
  903. case 't':
  904. return &Special{Prefix: "transaction clone for ", Val: v}
  905. }
  906. case 'r':
  907. return st.javaResource()
  908. default:
  909. st.fail("unrecognized special G name code")
  910. panic("not reached")
  911. }
  912. }
  913. }
  914. // <call-offset> ::= h <nv-offset> _
  915. // ::= v <v-offset> _
  916. //
  917. // <nv-offset> ::= <(offset) number>
  918. //
  919. // <v-offset> ::= <(offset) number> _ <(virtual offset) number>
  920. //
  921. // The c parameter, if not 0, is a character we just read which is the
  922. // start of the <call-offset>.
  923. //
  924. // We don't display the offset information anywhere.
  925. func (st *state) callOffset(c byte) {
  926. if c == 0 {
  927. if len(st.str) == 0 {
  928. st.fail("missing call offset")
  929. }
  930. c = st.str[0]
  931. st.advance(1)
  932. }
  933. switch c {
  934. case 'h':
  935. st.number()
  936. case 'v':
  937. st.number()
  938. if len(st.str) == 0 || st.str[0] != '_' {
  939. st.fail("expected _ after number")
  940. }
  941. st.advance(1)
  942. st.number()
  943. default:
  944. st.failEarlier("unrecognized call offset code", 1)
  945. }
  946. if len(st.str) == 0 || st.str[0] != '_' {
  947. st.fail("expected _ after call offset")
  948. }
  949. st.advance(1)
  950. }
  951. // builtinTypes maps the type letter to the type name.
  952. var builtinTypes = map[byte]string{
  953. 'a': "signed char",
  954. 'b': "bool",
  955. 'c': "char",
  956. 'd': "double",
  957. 'e': "long double",
  958. 'f': "float",
  959. 'g': "__float128",
  960. 'h': "unsigned char",
  961. 'i': "int",
  962. 'j': "unsigned int",
  963. 'l': "long",
  964. 'm': "unsigned long",
  965. 'n': "__int128",
  966. 'o': "unsigned __int128",
  967. 's': "short",
  968. 't': "unsigned short",
  969. 'v': "void",
  970. 'w': "wchar_t",
  971. 'x': "long long",
  972. 'y': "unsigned long long",
  973. 'z': "...",
  974. }
  975. // <type> ::= <builtin-type>
  976. // ::= <function-type>
  977. // ::= <class-enum-type>
  978. // ::= <array-type>
  979. // ::= <pointer-to-member-type>
  980. // ::= <template-param>
  981. // ::= <template-template-param> <template-args>
  982. // ::= <substitution>
  983. // ::= <CV-qualifiers> <type>
  984. // ::= P <type>
  985. // ::= R <type>
  986. // ::= O <type> (C++0x)
  987. // ::= C <type>
  988. // ::= G <type>
  989. // ::= U <source-name> <type>
  990. //
  991. // <builtin-type> ::= various one letter codes
  992. // ::= u <source-name>
  993. //
  994. // The isCast parameter is for a rather hideous parse. When we see a
  995. // tempate-param followed by a template-args, we need to decide
  996. // whether we have a template-param or a template-template-param.
  997. // Normally it is template-template-param, meaning that we pick up the
  998. // template arguments here. But, if we are parsing the type for a
  999. // cast operator, then the only way this can be
  1000. // template-template-param is if there is another set of template-args
  1001. // immediately after this set. That would look like this:
  1002. //
  1003. // <nested-name>
  1004. // -> <template-prefix> <template-args>
  1005. // -> <prefix> <template-unqualified-name> <template-args>
  1006. // -> <unqualified-name> <template-unqualified-name> <template-args>
  1007. // -> <source-name> <template-unqualified-name> <template-args>
  1008. // -> <source-name> <operator-name> <template-args>
  1009. // -> <source-name> cv <type> <template-args>
  1010. // -> <source-name> cv <template-template-param> <template-args> <template-args>
  1011. //
  1012. // Otherwise, we have this derivation:
  1013. //
  1014. // <nested-name>
  1015. // -> <template-prefix> <template-args>
  1016. // -> <prefix> <template-unqualified-name> <template-args>
  1017. // -> <unqualified-name> <template-unqualified-name> <template-args>
  1018. // -> <source-name> <template-unqualified-name> <template-args>
  1019. // -> <source-name> <operator-name> <template-args>
  1020. // -> <source-name> cv <type> <template-args>
  1021. // -> <source-name> cv <template-param> <template-args>
  1022. //
  1023. // in which the template-args are actually part of the prefix. For
  1024. // the special case where this arises, we pass in isCast as true.
  1025. // This function is then responsible for checking whether we see
  1026. // <template-param> <template-args> but there is not another following
  1027. // <template-args>. In that case, we reset the parse and just return
  1028. // the <template-param>.
  1029. func (st *state) demangleType(isCast bool) AST {
  1030. if len(st.str) == 0 {
  1031. st.fail("expected type")
  1032. }
  1033. addSubst := true
  1034. q := st.cvQualifiers()
  1035. if len(q) > 0 {
  1036. if len(st.str) == 0 {
  1037. st.fail("expected type")
  1038. }
  1039. // CV-qualifiers before a function type apply to
  1040. // 'this', so avoid adding the unqualified function
  1041. // type to the substitution list.
  1042. if st.str[0] == 'F' {
  1043. addSubst = false
  1044. }
  1045. }
  1046. var ret AST
  1047. // Use correct substitution for a template parameter.
  1048. var sub AST
  1049. if btype, ok := builtinTypes[st.str[0]]; ok {
  1050. ret = &BuiltinType{Name: btype}
  1051. st.advance(1)
  1052. if len(q) > 0 {
  1053. ret = &TypeWithQualifiers{Base: ret, Qualifiers: q}
  1054. st.subs.add(ret)
  1055. }
  1056. return ret
  1057. }
  1058. c := st.str[0]
  1059. switch c {
  1060. case 'u':
  1061. st.advance(1)
  1062. ret = st.sourceName()
  1063. case 'F':
  1064. ret = st.functionType()
  1065. case 'N', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  1066. ret = st.name()
  1067. case 'A':
  1068. ret = st.arrayType(isCast)
  1069. case 'M':
  1070. ret = st.pointerToMemberType(isCast)
  1071. case 'T':
  1072. ret = st.templateParam()
  1073. if len(st.str) > 0 && st.str[0] == 'I' {
  1074. // See the function comment to explain this.
  1075. if !isCast {
  1076. st.subs.add(ret)
  1077. args := st.templateArgs()
  1078. ret = &Template{Name: ret, Args: args}
  1079. } else {
  1080. save := st.copy()
  1081. var args []AST
  1082. failed := false
  1083. func() {
  1084. defer func() {
  1085. if r := recover(); r != nil {
  1086. if _, ok := r.(demangleErr); ok {
  1087. failed = true
  1088. } else {
  1089. panic(r)
  1090. }
  1091. }
  1092. }()
  1093. args = st.templateArgs()
  1094. }()
  1095. if !failed && len(st.str) > 0 && st.str[0] == 'I' {
  1096. st.subs.add(ret)
  1097. ret = &Template{Name: ret, Args: args}
  1098. } else {
  1099. // Reset back to before we started
  1100. // reading the template arguments.
  1101. // They will be read again by
  1102. // st.prefix.
  1103. *st = *save
  1104. }
  1105. }
  1106. }
  1107. case 'S':
  1108. // If this is a special substitution, then it
  1109. // is the start of <class-enum-type>.
  1110. var c2 byte
  1111. if len(st.str) > 1 {
  1112. c2 = st.str[1]
  1113. }
  1114. if isDigit(c2) || c2 == '_' || isUpper(c2) {
  1115. ret = st.substitution(false)
  1116. if len(st.str) == 0 || st.str[0] != 'I' {
  1117. addSubst = false
  1118. } else {
  1119. args := st.templateArgs()
  1120. ret = &Template{Name: ret, Args: args}
  1121. }
  1122. } else {
  1123. ret = st.name()
  1124. // This substitution is not itself a
  1125. // substitution candidate, unless template
  1126. // arguments were added.
  1127. if ret == subAST[c2] || ret == verboseAST[c2] {
  1128. addSubst = false
  1129. }
  1130. }
  1131. case 'O', 'P', 'R', 'C', 'G':
  1132. st.advance(1)
  1133. t := st.demangleType(isCast)
  1134. switch c {
  1135. case 'O':
  1136. ret = &RvalueReferenceType{Base: t}
  1137. case 'P':
  1138. ret = &PointerType{Base: t}
  1139. case 'R':
  1140. ret = &ReferenceType{Base: t}
  1141. case 'C':
  1142. ret = &ComplexType{Base: t}
  1143. case 'G':
  1144. ret = &ImaginaryType{Base: t}
  1145. }
  1146. case 'U':
  1147. st.advance(1)
  1148. n := st.sourceName()
  1149. if len(st.str) > 0 && st.str[0] == 'I' {
  1150. args := st.templateArgs()
  1151. n = &Template{Name: n, Args: args}
  1152. }
  1153. t := st.demangleType(isCast)
  1154. ret = &VendorQualifier{Qualifier: n, Type: t}
  1155. case 'D':
  1156. st.advance(1)
  1157. if len(st.str) == 0 {
  1158. st.fail("expected D code for type")
  1159. }
  1160. addSubst = false
  1161. c2 := st.str[0]
  1162. st.advance(1)
  1163. switch c2 {
  1164. case 'T', 't':
  1165. // decltype(expression)
  1166. ret = st.expression()
  1167. if len(st.str) == 0 || st.str[0] != 'E' {
  1168. st.fail("expected E after expression in type")
  1169. }
  1170. st.advance(1)
  1171. ret = &Decltype{Expr: ret}
  1172. addSubst = true
  1173. case 'p':
  1174. t := st.demangleType(isCast)
  1175. pack := st.findArgumentPack(t)
  1176. ret = &PackExpansion{Base: t, Pack: pack}
  1177. addSubst = true
  1178. case 'a':
  1179. ret = &Name{Name: "auto"}
  1180. case 'f':
  1181. ret = &BuiltinType{Name: "decimal32"}
  1182. case 'd':
  1183. ret = &BuiltinType{Name: "decimal64"}
  1184. case 'e':
  1185. ret = &BuiltinType{Name: "decimal128"}
  1186. case 'h':
  1187. ret = &BuiltinType{Name: "half"}
  1188. case 's':
  1189. ret = &BuiltinType{Name: "char16_t"}
  1190. case 'i':
  1191. ret = &BuiltinType{Name: "char32_t"}
  1192. case 'n':
  1193. ret = &BuiltinType{Name: "decltype(nullptr)"}
  1194. case 'F':
  1195. accum := false
  1196. if len(st.str) > 0 && isDigit(st.str[0]) {
  1197. accum = true
  1198. // We don't care about the bits.
  1199. _ = st.number()
  1200. }
  1201. base := st.demangleType(isCast)
  1202. if len(st.str) > 0 && isDigit(st.str[0]) {
  1203. // We don't care about the bits.
  1204. st.number()
  1205. }
  1206. sat := false
  1207. if len(st.str) > 0 {
  1208. if st.str[0] == 's' {
  1209. sat = true
  1210. }
  1211. st.advance(1)
  1212. }
  1213. ret = &FixedType{Base: base, Accum: accum, Sat: sat}
  1214. case 'v':
  1215. ret = st.vectorType(isCast)
  1216. addSubst = true
  1217. default:
  1218. st.fail("unrecognized D code in type")
  1219. }
  1220. default:
  1221. st.fail("unrecognized type code")
  1222. }
  1223. if addSubst {
  1224. if sub != nil {
  1225. st.subs.add(sub)
  1226. } else {
  1227. st.subs.add(ret)
  1228. }
  1229. }
  1230. if len(q) > 0 {
  1231. if _, ok := ret.(*FunctionType); ok {
  1232. ret = &MethodWithQualifiers{Method: ret, Qualifiers: q, RefQualifier: ""}
  1233. } else if mwq, ok := ret.(*MethodWithQualifiers); ok {
  1234. // Merge adjacent qualifiers. This case
  1235. // happens with a function with a trailing
  1236. // ref-qualifier.
  1237. mwq.Qualifiers = mergeQualifiers(q, mwq.Qualifiers)
  1238. } else {
  1239. // Merge adjacent qualifiers. This case
  1240. // happens with multi-dimensional array types.
  1241. if qsub, ok := ret.(*TypeWithQualifiers); ok {
  1242. q = mergeQualifiers(q, qsub.Qualifiers)
  1243. ret = qsub.Base
  1244. }
  1245. ret = &TypeWithQualifiers{Base: ret, Qualifiers: q}
  1246. }
  1247. st.subs.add(ret)
  1248. }
  1249. return ret
  1250. }
  1251. // mergeQualifiers merges two qualifer lists into one.
  1252. func mergeQualifiers(q1, q2 Qualifiers) Qualifiers {
  1253. m := make(map[string]bool)
  1254. for _, qual := range q1 {
  1255. m[qual] = true
  1256. }
  1257. for _, qual := range q2 {
  1258. if !m[qual] {
  1259. q1 = append(q1, qual)
  1260. m[qual] = true
  1261. }
  1262. }
  1263. return q1
  1264. }
  1265. // qualifiers maps from the character used in the mangled name to the
  1266. // string to print.
  1267. var qualifiers = map[byte]string{
  1268. 'r': "restrict",
  1269. 'V': "volatile",
  1270. 'K': "const",
  1271. }
  1272. // <CV-qualifiers> ::= [r] [V] [K]
  1273. func (st *state) cvQualifiers() Qualifiers {
  1274. var q Qualifiers
  1275. for len(st.str) > 0 {
  1276. if qv, ok := qualifiers[st.str[0]]; ok {
  1277. q = append([]string{qv}, q...)
  1278. st.advance(1)
  1279. } else if len(st.str) > 1 && st.str[:2] == "Dx" {
  1280. q = append([]string{"transaction_safe"}, q...)
  1281. st.advance(2)
  1282. } else {
  1283. break
  1284. }
  1285. }
  1286. return q
  1287. }
  1288. // <ref-qualifier> ::= R
  1289. // ::= O
  1290. func (st *state) refQualifier() string {
  1291. if len(st.str) > 0 {
  1292. switch st.str[0] {
  1293. case 'R':
  1294. st.advance(1)
  1295. return "&"
  1296. case 'O':
  1297. st.advance(1)
  1298. return "&&"
  1299. }
  1300. }
  1301. return ""
  1302. }
  1303. // <type>+
  1304. func (st *state) parmlist() []AST {
  1305. var ret []AST
  1306. for {
  1307. if len(st.str) < 1 {
  1308. break
  1309. }
  1310. if st.str[0] == 'E' || st.str[0] == '.' {
  1311. break
  1312. }
  1313. if (st.str[0] == 'R' || st.str[0] == 'O') && len(st.str) > 1 && st.str[1] == 'E' {
  1314. // This is a function ref-qualifier.
  1315. break
  1316. }
  1317. ptype := st.demangleType(false)
  1318. ret = append(ret, ptype)
  1319. }
  1320. // There should always be at least one type. A function that
  1321. // takes no arguments will have a single parameter type
  1322. // "void".
  1323. if len(ret) == 0 {
  1324. st.fail("expected at least one type in type list")
  1325. }
  1326. // Omit a single parameter type void.
  1327. if len(ret) == 1 {
  1328. if bt, ok := ret[0].(*BuiltinType); ok && bt.Name == "void" {
  1329. ret = nil
  1330. }
  1331. }
  1332. return ret
  1333. }
  1334. // <function-type> ::= F [Y] <bare-function-type> [<ref-qualifier>] E
  1335. func (st *state) functionType() AST {
  1336. st.checkChar('F')
  1337. if len(st.str) > 0 && st.str[0] == 'Y' {
  1338. // Function has C linkage. We don't print this.
  1339. st.advance(1)
  1340. }
  1341. ret := st.bareFunctionType(true)
  1342. r := st.refQualifier()
  1343. if r != "" {
  1344. ret = &MethodWithQualifiers{Method: ret, Qualifiers: nil, RefQualifier: r}
  1345. }
  1346. if len(st.str) == 0 || st.str[0] != 'E' {
  1347. st.fail("expected E after function type")
  1348. }
  1349. st.advance(1)
  1350. return ret
  1351. }
  1352. // <bare-function-type> ::= [J]<type>+
  1353. func (st *state) bareFunctionType(hasReturnType bool) AST {
  1354. if len(st.str) > 0 && st.str[0] == 'J' {
  1355. hasReturnType = true
  1356. st.advance(1)
  1357. }
  1358. var returnType AST
  1359. if hasReturnType {
  1360. returnType = st.demangleType(false)
  1361. }
  1362. types := st.parmlist()
  1363. return &FunctionType{Return: returnType, Args: types}
  1364. }
  1365. // <array-type> ::= A <(positive dimension) number> _ <(element) type>
  1366. // ::= A [<(dimension) expression>] _ <(element) type>
  1367. func (st *state) arrayType(isCast bool) AST {
  1368. st.checkChar('A')
  1369. if len(st.str) == 0 {
  1370. st.fail("missing array dimension")
  1371. }
  1372. var dim AST
  1373. if st.str[0] == '_' {
  1374. dim = &Name{Name: ""}
  1375. } else if isDigit(st.str[0]) {
  1376. i := 1
  1377. for len(st.str) > i && isDigit(st.str[i]) {
  1378. i++
  1379. }
  1380. dim = &Name{Name: st.str[:i]}
  1381. st.advance(i)
  1382. } else {
  1383. dim = st.expression()
  1384. }
  1385. if len(st.str) == 0 || st.str[0] != '_' {
  1386. st.fail("expected _ after dimension")
  1387. }
  1388. st.advance(1)
  1389. t := st.demangleType(isCast)
  1390. arr := &ArrayType{Dimension: dim, Element: t}
  1391. // Qualifiers on the element of an array type go on the whole
  1392. // array type.
  1393. if q, ok := arr.Element.(*TypeWithQualifiers); ok {
  1394. return &TypeWithQualifiers{Base: &ArrayType{Dimension: dim, Element: q.Base}, Qualifiers: q.Qualifiers}
  1395. }
  1396. return arr
  1397. }
  1398. // <vector-type> ::= Dv <number> _ <type>
  1399. // ::= Dv _ <expression> _ <type>
  1400. func (st *state) vectorType(isCast bool) AST {
  1401. if len(st.str) == 0 {
  1402. st.fail("expected vector dimension")
  1403. }
  1404. var dim AST
  1405. if st.str[0] == '_' {
  1406. st.advance(1)
  1407. dim = st.expression()
  1408. } else {
  1409. num := st.number()
  1410. dim = &Name{Name: fmt.Sprintf("%d", num)}
  1411. }
  1412. if len(st.str) == 0 || st.str[0] != '_' {
  1413. st.fail("expected _ after vector dimension")
  1414. }
  1415. st.advance(1)
  1416. t := st.demangleType(isCast)
  1417. return &VectorType{Dimension: dim, Base: t}
  1418. }
  1419. // <pointer-to-member-type> ::= M <(class) type> <(member) type>
  1420. func (st *state) pointerToMemberType(isCast bool) AST {
  1421. st.checkChar('M')
  1422. cl := st.demangleType(false)
  1423. // The ABI says, "The type of a non-static member function is
  1424. // considered to be different, for the purposes of
  1425. // substitution, from the type of a namespace-scope or static
  1426. // member function whose type appears similar. The types of
  1427. // two non-static member functions are considered to be
  1428. // different, for the purposes of substitution, if the
  1429. // functions are members of different classes. In other words,
  1430. // for the purposes of substitution, the class of which the
  1431. // function is a member is considered part of the type of
  1432. // function."
  1433. //
  1434. // For a pointer to member function, this call to demangleType
  1435. // will end up adding a (possibly qualified) non-member
  1436. // function type to the substitution table, which is not
  1437. // correct; however, the member function type will never be
  1438. // used in a substitution, so putting the wrong type in the
  1439. // substitution table is harmless.
  1440. mem := st.demangleType(isCast)
  1441. return &PtrMem{Class: cl, Member: mem}
  1442. }
  1443. // <non-negative number> _ */
  1444. func (st *state) compactNumber() int {
  1445. if len(st.str) == 0 {
  1446. st.fail("missing index")
  1447. }
  1448. if st.str[0] == '_' {
  1449. st.advance(1)
  1450. return 0
  1451. } else if st.str[0] == 'n' {
  1452. st.fail("unexpected negative number")
  1453. }
  1454. n := st.number()
  1455. if len(st.str) == 0 || st.str[0] != '_' {
  1456. st.fail("missing underscore after number")
  1457. }
  1458. st.advance(1)
  1459. return n + 1
  1460. }
  1461. // <template-param> ::= T_
  1462. // ::= T <(parameter-2 non-negative) number> _
  1463. //
  1464. // When a template parameter is a substitution candidate, any
  1465. // reference to that substitution refers to the template parameter
  1466. // with the same index in the currently active template, not to
  1467. // whatever the template parameter would be expanded to here. We sort
  1468. // this out in substitution and simplify.
  1469. func (st *state) templateParam() AST {
  1470. if len(st.templates) == 0 {
  1471. st.fail("template parameter not in scope of template")
  1472. }
  1473. off := st.off
  1474. st.checkChar('T')
  1475. n := st.compactNumber()
  1476. template := st.templates[len(st.templates)-1]
  1477. if template == nil {
  1478. // We are parsing a cast operator. If the cast is
  1479. // itself a template, then this is a forward
  1480. // reference. Fill it in later.
  1481. return &TemplateParam{Index: n, Template: nil}
  1482. }
  1483. if n >= len(template.Args) {
  1484. st.failEarlier(fmt.Sprintf("template index out of range (%d >= %d)", n, len(template.Args)), st.off-off)
  1485. }
  1486. return &TemplateParam{Index: n, Template: template}
  1487. }
  1488. // setTemplate sets the Template field of any TemplateParam's in a.
  1489. // This handles the forward referencing template parameters found in
  1490. // cast operators.
  1491. func (st *state) setTemplate(a AST, tmpl *Template) {
  1492. a.Traverse(func(a AST) bool {
  1493. switch a := a.(type) {
  1494. case *TemplateParam:
  1495. if a.Template != nil {
  1496. panic("internal error")
  1497. }
  1498. if tmpl == nil {
  1499. st.fail("cast template parameter not in scope of template")
  1500. }
  1501. if a.Index >= len(tmpl.Args) {
  1502. st.fail(fmt.Sprintf("cast template index out of range (%d >= %d)", a.Index, len(tmpl.Args)))
  1503. }
  1504. a.Template = tmpl
  1505. return false
  1506. default:
  1507. return true
  1508. }
  1509. })
  1510. }
  1511. // <template-args> ::= I <template-arg>+ E
  1512. func (st *state) templateArgs() []AST {
  1513. if len(st.str) == 0 || (st.str[0] != 'I' && st.str[0] != 'J') {
  1514. panic("internal error")
  1515. }
  1516. st.advance(1)
  1517. var ret []AST
  1518. for len(st.str) == 0 || st.str[0] != 'E' {
  1519. arg := st.templateArg()
  1520. ret = append(ret, arg)
  1521. }
  1522. st.advance(1)
  1523. return ret
  1524. }
  1525. // <template-arg> ::= <type>
  1526. // ::= X <expression> E
  1527. // ::= <expr-primary>
  1528. func (st *state) templateArg() AST {
  1529. if len(st.str) == 0 {
  1530. st.fail("missing template argument")
  1531. }
  1532. switch st.str[0] {
  1533. case 'X':
  1534. st.advance(1)
  1535. expr := st.expression()
  1536. if len(st.str) == 0 || st.str[0] != 'E' {
  1537. st.fail("missing end of expression")
  1538. }
  1539. st.advance(1)
  1540. return expr
  1541. case 'L':
  1542. return st.exprPrimary()
  1543. case 'I', 'J':
  1544. args := st.templateArgs()
  1545. return &ArgumentPack{Args: args}
  1546. default:
  1547. return st.demangleType(false)
  1548. }
  1549. }
  1550. // exprList parses a sequence of expressions up to a terminating character.
  1551. func (st *state) exprList(stop byte) AST {
  1552. if len(st.str) > 0 && st.str[0] == stop {
  1553. st.advance(1)
  1554. return &ExprList{Exprs: nil}
  1555. }
  1556. var exprs []AST
  1557. for {
  1558. e := st.expression()
  1559. exprs = append(exprs, e)
  1560. if len(st.str) > 0 && st.str[0] == stop {
  1561. st.advance(1)
  1562. break
  1563. }
  1564. }
  1565. return &ExprList{Exprs: exprs}
  1566. }
  1567. // <expression> ::= <(unary) operator-name> <expression>
  1568. // ::= <(binary) operator-name> <expression> <expression>
  1569. // ::= <(trinary) operator-name> <expression> <expression> <expression>
  1570. // ::= cl <expression>+ E
  1571. // ::= st <type>
  1572. // ::= <template-param>
  1573. // ::= sr <type> <unqualified-name>
  1574. // ::= sr <type> <unqualified-name> <template-args>
  1575. // ::= <expr-primary>
  1576. func (st *state) expression() AST {
  1577. if len(st.str) == 0 {
  1578. st.fail("expected expression")
  1579. }
  1580. if st.str[0] == 'L' {
  1581. return st.exprPrimary()
  1582. } else if st.str[0] == 'T' {
  1583. return st.templateParam()
  1584. } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'r' {
  1585. st.advance(2)
  1586. if len(st.str) == 0 {
  1587. st.fail("expected unresolved type")
  1588. }
  1589. switch st.str[0] {
  1590. case 'T', 'D', 'S':
  1591. t := st.demangleType(false)
  1592. n := st.unqualifiedName()
  1593. n = &Qualified{Scope: t, Name: n, LocalName: false}
  1594. if len(st.str) > 0 && st.str[0] == 'I' {
  1595. args := st.templateArgs()
  1596. n = &Template{Name: n, Args: args}
  1597. }
  1598. return n
  1599. default:
  1600. var s AST
  1601. if st.str[0] == 'N' {
  1602. st.advance(1)
  1603. s = st.demangleType(false)
  1604. }
  1605. for len(st.str) == 0 || st.str[0] != 'E' {
  1606. // GCC does not seem to follow the ABI here.
  1607. // It can emit type/name without an 'E'.
  1608. if s != nil && len(st.str) > 0 && !isDigit(st.str[0]) {
  1609. if q, ok := s.(*Qualified); ok {
  1610. a := q.Scope
  1611. if t, ok := a.(*Template); ok {
  1612. st.subs.add(t.Name)
  1613. st.subs.add(t)
  1614. } else {
  1615. st.subs.add(a)
  1616. }
  1617. return s
  1618. }
  1619. }
  1620. n := st.sourceName()
  1621. if len(st.str) > 0 && st.str[0] == 'I' {
  1622. args := st.templateArgs()
  1623. n = &Template{Name: n, Args: args}
  1624. }
  1625. if s == nil {
  1626. s = n
  1627. } else {
  1628. s = &Qualified{Scope: s, Name: n, LocalName: false}
  1629. }
  1630. }
  1631. if s == nil {
  1632. st.fail("missing scope in unresolved name")
  1633. }
  1634. st.advance(1)
  1635. // TODO(iant): Handle "on" and "dn".
  1636. n := st.sourceName()
  1637. if len(st.str) > 0 && st.str[0] == 'I' {
  1638. args := st.templateArgs()
  1639. n = &Template{Name: n, Args: args}
  1640. }
  1641. return &Qualified{Scope: s, Name: n, LocalName: false}
  1642. }
  1643. } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 'p' {
  1644. st.advance(2)
  1645. e := st.expression()
  1646. pack := st.findArgumentPack(e)
  1647. return &PackExpansion{Base: e, Pack: pack}
  1648. } else if st.str[0] == 'f' && len(st.str) > 1 && st.str[1] == 'p' {
  1649. st.advance(2)
  1650. if len(st.str) > 0 && st.str[0] == 'T' {
  1651. st.advance(1)
  1652. return &FunctionParam{Index: 0}
  1653. } else {
  1654. index := st.compactNumber()
  1655. return &FunctionParam{Index: index + 1}
  1656. }
  1657. } else if isDigit(st.str[0]) || (st.str[0] == 'o' && len(st.str) > 1 && st.str[1] == 'n') {
  1658. if st.str[0] == 'o' {
  1659. // Skip operator function ID.
  1660. st.advance(2)
  1661. }
  1662. n := st.unqualifiedName()
  1663. if len(st.str) > 0 && st.str[0] == 'I' {
  1664. args := st.templateArgs()
  1665. n = &Template{Name: n, Args: args}
  1666. }
  1667. return n
  1668. } else if (st.str[0] == 'i' || st.str[0] == 't') && len(st.str) > 1 && st.str[1] == 'l' {
  1669. // Brace-enclosed initializer list.
  1670. c := st.str[0]
  1671. st.advance(2)
  1672. var t AST
  1673. if c == 't' {
  1674. t = st.demangleType(false)
  1675. }
  1676. exprs := st.exprList('E')
  1677. return &InitializerList{Type: t, Exprs: exprs}
  1678. } else if st.str[0] == 's' && len(st.str) > 1 && st.str[1] == 't' {
  1679. o, _ := st.operatorName(true)
  1680. t := st.demangleType(false)
  1681. return &Unary{Op: o, Expr: t, Suffix: false, SizeofType: true}
  1682. } else {
  1683. if len(st.str) < 2 {
  1684. st.fail("missing operator code")
  1685. }
  1686. code := st.str[:2]
  1687. o, args := st.operatorName(true)
  1688. switch args {
  1689. case 0:
  1690. return &Nullary{Op: o}
  1691. case 1:
  1692. suffix := false
  1693. if code == "pp" || code == "mm" {
  1694. if len(st.str) > 0 && st.str[0] == '_' {
  1695. st.advance(1)
  1696. } else {
  1697. suffix = true
  1698. }
  1699. }
  1700. var operand AST
  1701. if _, ok := o.(*Cast); ok && len(st.str) > 0 && st.str[0] == '_' {
  1702. st.advance(1)
  1703. operand = st.exprList('E')
  1704. } else {
  1705. operand = st.expression()
  1706. }
  1707. return &Unary{Op: o, Expr: operand, Suffix: suffix, SizeofType: false}
  1708. case 2:
  1709. var left, right AST
  1710. if code == "sc" || code == "dc" || code == "cc" || code == "rc" {
  1711. left = st.demangleType(false)
  1712. } else {
  1713. left = st.expression()
  1714. }
  1715. if code == "cl" {
  1716. right = st.exprList('E')
  1717. } else if code == "dt" || code == "pt" {
  1718. right = st.unqualifiedName()
  1719. if len(st.str) > 0 && st.str[0] == 'I' {
  1720. args := st.templateArgs()
  1721. right = &Template{Name: right, Args: args}
  1722. }
  1723. } else {
  1724. right = st.expression()
  1725. }
  1726. return &Binary{Op: o, Left: left, Right: right}
  1727. case 3:
  1728. if code[0] == 'n' {
  1729. if code[1] != 'w' && code[1] != 'a' {
  1730. panic("internal error")
  1731. }
  1732. place := st.exprList('_')
  1733. if place.(*ExprList).Exprs == nil {
  1734. place = nil
  1735. }
  1736. t := st.demangleType(false)
  1737. var ini AST
  1738. if len(st.str) > 0 && st.str[0] == 'E' {
  1739. st.advance(1)
  1740. } else if len(st.str) > 1 && st.str[0] == 'p' && st.str[1] == 'i' {
  1741. // Parenthesized initializer.
  1742. st.advance(2)
  1743. ini = st.exprList('E')
  1744. } else if len(st.str) > 1 && st.str[0] == 'i' && st.str[1] == 'l' {
  1745. // Initializer list.
  1746. ini = st.expression()
  1747. } else {
  1748. st.fail("unrecognized new initializer")
  1749. }
  1750. return &New{Op: o, Place: place, Type: t, Init: ini}
  1751. } else {
  1752. first := st.expression()
  1753. second := st.expression()
  1754. third := st.expression()
  1755. return &Trinary{Op: o, First: first, Second: second, Third: third}
  1756. }
  1757. default:
  1758. st.fail(fmt.Sprintf("unsupported number of operator arguments: %d", args))
  1759. panic("not reached")
  1760. }
  1761. }
  1762. }
  1763. // <expr-primary> ::= L <type> <(value) number> E
  1764. // ::= L <type> <(value) float> E
  1765. // ::= L <mangled-name> E
  1766. func (st *state) exprPrimary() AST {
  1767. st.checkChar('L')
  1768. if len(st.str) == 0 {
  1769. st.fail("expected primary expression")
  1770. }
  1771. // Check for 'Z' here because g++ incorrectly omitted the
  1772. // underscore until -fabi-version=3.
  1773. var ret AST
  1774. if st.str[0] == '_' || st.str[0] == 'Z' {
  1775. if st.str[0] == '_' {
  1776. st.advance(1)
  1777. }
  1778. if len(st.str) == 0 || st.str[0] != 'Z' {
  1779. st.fail("expected mangled name")
  1780. }
  1781. st.advance(1)
  1782. ret = st.encoding(true)
  1783. } else {
  1784. t := st.demangleType(false)
  1785. neg := false
  1786. if len(st.str) > 0 && st.str[0] == 'n' {
  1787. neg = true
  1788. st.advance(1)
  1789. }
  1790. i := 0
  1791. for len(st.str) > 0 && st.str[i] != 'E' {
  1792. i++
  1793. }
  1794. val := st.str[:i]
  1795. st.advance(i)
  1796. ret = &Literal{Type: t, Val: val, Neg: neg}
  1797. }
  1798. if len(st.str) == 0 || st.str[0] != 'E' {
  1799. st.fail("expected E after literal")
  1800. }
  1801. st.advance(1)
  1802. return ret
  1803. }
  1804. // <discriminator> ::= _ <(non-negative) number>
  1805. func (st *state) discriminator(a AST) AST {
  1806. if len(st.str) == 0 || st.str[0] != '_' {
  1807. return a
  1808. }
  1809. off := st.off
  1810. st.advance(1)
  1811. d := st.number()
  1812. if d < 0 {
  1813. st.failEarlier("invalid negative discriminator", st.off-off)
  1814. }
  1815. // We don't currently print out the discriminator, so we don't
  1816. // save it.
  1817. return a
  1818. }
  1819. // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
  1820. func (st *state) closureTypeName() AST {
  1821. st.checkChar('U')
  1822. st.checkChar('l')
  1823. types := st.parmlist()
  1824. if len(st.str) == 0 || st.str[0] != 'E' {
  1825. st.fail("expected E after closure type name")
  1826. }
  1827. st.advance(1)
  1828. num := st.compactNumber()
  1829. ret := &Closure{Types: types, Num: num}
  1830. st.subs.add(ret)
  1831. return ret
  1832. }
  1833. // <unnamed-type-name> ::= Ut [ <nonnegative number> ] _
  1834. func (st *state) unnamedTypeName() AST {
  1835. st.checkChar('U')
  1836. st.checkChar('t')
  1837. num := st.compactNumber()
  1838. ret := &UnnamedType{Num: num}
  1839. st.subs.add(ret)
  1840. return ret
  1841. }
  1842. // Recognize a clone suffix. These are not part of the mangling API,
  1843. // but are added by GCC when cloning functions.
  1844. func (st *state) cloneSuffix(a AST) AST {
  1845. i := 0
  1846. if len(st.str) > 1 && st.str[0] == '.' && (isLower(st.str[1]) || st.str[1] == '_') {
  1847. i += 2
  1848. for len(st.str) > i && (isLower(st.str[i]) || st.str[i] == '_') {
  1849. i++
  1850. }
  1851. }
  1852. for len(st.str) > i+1 && st.str[i] == '.' && isDigit(st.str[i+1]) {
  1853. i += 2
  1854. for len(st.str) > i && isDigit(st.str[i]) {
  1855. i++
  1856. }
  1857. }
  1858. suffix := st.str[:i]
  1859. st.advance(i)
  1860. return &Clone{Base: a, Suffix: suffix}
  1861. }
  1862. // substitutions is the list of substitution candidates that may
  1863. // appear later in the string.
  1864. type substitutions []AST
  1865. // add adds a new substitution candidate.
  1866. func (subs *substitutions) add(a AST) {
  1867. *subs = append(*subs, a)
  1868. }
  1869. // subAST maps standard substitution codes to the corresponding AST.
  1870. var subAST = map[byte]AST{
  1871. 't': &Name{Name: "std"},
  1872. 'a': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "allocator"}},
  1873. 'b': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_string"}},
  1874. 's': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "string"}},
  1875. 'i': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "istream"}},
  1876. 'o': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "ostream"}},
  1877. 'd': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "iostream"}},
  1878. }
  1879. // verboseAST maps standard substitution codes to the long form of the
  1880. // corresponding AST. We use this when the Verbose option is used, to
  1881. // match the standard demangler.
  1882. var verboseAST = map[byte]AST{
  1883. 't': &Name{Name: "std"},
  1884. 'a': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "allocator"}},
  1885. 'b': &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_string"}},
  1886. // std::basic_string<char, std::char_traits<char>, std::allocator<char> >
  1887. 's': &Template{
  1888. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_string"}},
  1889. Args: []AST{
  1890. &BuiltinType{Name: "char"},
  1891. &Template{
  1892. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
  1893. Args: []AST{&BuiltinType{Name: "char"}}},
  1894. &Template{
  1895. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "allocator"}},
  1896. Args: []AST{&BuiltinType{Name: "char"}}}}},
  1897. // std::basic_istream<char, std::char_traits<char> >
  1898. 'i': &Template{
  1899. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_istream"}},
  1900. Args: []AST{
  1901. &BuiltinType{Name: "char"},
  1902. &Template{
  1903. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
  1904. Args: []AST{&BuiltinType{Name: "char"}}}}},
  1905. // std::basic_ostream<char, std::char_traits<char> >
  1906. 'o': &Template{
  1907. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_ostream"}},
  1908. Args: []AST{
  1909. &BuiltinType{Name: "char"},
  1910. &Template{
  1911. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
  1912. Args: []AST{&BuiltinType{Name: "char"}}}}},
  1913. // std::basic_iostream<char, std::char_traits<char> >
  1914. 'd': &Template{
  1915. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "basic_iostream"}},
  1916. Args: []AST{
  1917. &BuiltinType{Name: "char"},
  1918. &Template{
  1919. Name: &Qualified{Scope: &Name{Name: "std"}, Name: &Name{Name: "char_traits"}},
  1920. Args: []AST{&BuiltinType{Name: "char"}}}}},
  1921. }
  1922. // <substitution> ::= S <seq-id> _
  1923. // ::= S_
  1924. // ::= St
  1925. // ::= Sa
  1926. // ::= Sb
  1927. // ::= Ss
  1928. // ::= Si
  1929. // ::= So
  1930. // ::= Sd
  1931. func (st *state) substitution(forPrefix bool) AST {
  1932. st.checkChar('S')
  1933. if len(st.str) == 0 {
  1934. st.fail("missing substitution index")
  1935. }
  1936. c := st.str[0]
  1937. st.advance(1)
  1938. dec := 1
  1939. if c == '_' || isDigit(c) || isUpper(c) {
  1940. id := 0
  1941. if c != '_' {
  1942. for c != '_' {
  1943. // Don't overflow a 32-bit int.
  1944. if id >= 0x80000000/36-36 {
  1945. st.fail("substitution index overflow")
  1946. }
  1947. if isDigit(c) {
  1948. id = id*36 + int(c-'0')
  1949. } else if isUpper(c) {
  1950. id = id*36 + int(c-'A') + 10
  1951. } else {
  1952. st.fail("invalid character in substitution index")
  1953. }
  1954. if len(st.str) == 0 {
  1955. st.fail("missing end to substitution index")
  1956. }
  1957. c = st.str[0]
  1958. st.advance(1)
  1959. dec++
  1960. }
  1961. id++
  1962. }
  1963. if id >= len(st.subs) {
  1964. st.failEarlier(fmt.Sprintf("substitution index out of range (%d >= %d)", id, len(st.subs)), dec)
  1965. }
  1966. ret := st.subs[id]
  1967. // We need to update any references to template
  1968. // parameters to refer to the currently active
  1969. // template.
  1970. copy := func(a AST) AST {
  1971. tp, ok := a.(*TemplateParam)
  1972. if !ok {
  1973. return nil
  1974. }
  1975. if len(st.templates) == 0 {
  1976. st.failEarlier("substituted template parameter not in scope of template", dec)
  1977. }
  1978. template := st.templates[len(st.templates)-1]
  1979. if template == nil {
  1980. // This template parameter is within
  1981. // the scope of a cast operator.
  1982. return &TemplateParam{Index: tp.Index, Template: nil}
  1983. }
  1984. if tp.Index >= len(template.Args) {
  1985. st.failEarlier(fmt.Sprintf("substituted template index out of range (%d >= %d)", tp.Index, len(template.Args)), dec)
  1986. }
  1987. return &TemplateParam{Index: tp.Index, Template: template}
  1988. }
  1989. skip := func(a AST) bool {
  1990. if _, ok := a.(*Typed); ok {
  1991. return true
  1992. }
  1993. return false
  1994. }
  1995. if c := ret.Copy(copy, skip); c != nil {
  1996. return c
  1997. }
  1998. return ret
  1999. } else {
  2000. m := subAST
  2001. if st.verbose {
  2002. m = verboseAST
  2003. }
  2004. // For compatibility with the standard demangler, use
  2005. // a longer name for a constructor or destructor.
  2006. if forPrefix && len(st.str) > 0 && (st.str[0] == 'C' || st.str[0] == 'D') {
  2007. m = verboseAST
  2008. }
  2009. a, ok := m[c]
  2010. if !ok {
  2011. st.failEarlier("unrecognized substitution code", 1)
  2012. }
  2013. if len(st.str) > 0 && st.str[0] == 'B' {
  2014. a = st.taggedName(a)
  2015. }
  2016. return a
  2017. }
  2018. }
  2019. // isDigit returns whetner c is a digit for demangling purposes.
  2020. func isDigit(c byte) bool {
  2021. return c >= '0' && c <= '9'
  2022. }
  2023. // isUpper returns whether c is an upper case letter for demangling purposes.
  2024. func isUpper(c byte) bool {
  2025. return c >= 'A' && c <= 'Z'
  2026. }
  2027. // isLower returns whether c is a lower case letter for demangling purposes.
  2028. func isLower(c byte) bool {
  2029. return c >= 'a' && c <= 'z'
  2030. }
  2031. // simplify replaces template parameters with their expansions, and
  2032. // merges qualifiers.
  2033. func simplify(a AST) AST {
  2034. skip := func(a AST) bool {
  2035. return false
  2036. }
  2037. if r := a.Copy(simplifyOne, skip); r != nil {
  2038. return r
  2039. }
  2040. return a
  2041. }
  2042. // simplifyOne simplifies a single AST. It returns nil if there is
  2043. // nothing to do.
  2044. func simplifyOne(a AST) AST {
  2045. switch a := a.(type) {
  2046. case *TemplateParam:
  2047. if a.Template == nil || a.Index >= len(a.Template.Args) {
  2048. panic("internal error")
  2049. }
  2050. return a.Template.Args[a.Index]
  2051. case *MethodWithQualifiers:
  2052. if m, ok := a.Method.(*MethodWithQualifiers); ok {
  2053. ref := a.RefQualifier
  2054. if ref == "" {
  2055. ref = m.RefQualifier
  2056. } else if m.RefQualifier != "" {
  2057. if ref == "&" || m.RefQualifier == "&" {
  2058. ref = "&"
  2059. }
  2060. }
  2061. return &MethodWithQualifiers{Method: m.Method, Qualifiers: mergeQualifiers(a.Qualifiers, m.Qualifiers), RefQualifier: ref}
  2062. }
  2063. if t, ok := a.Method.(*TypeWithQualifiers); ok {
  2064. return &MethodWithQualifiers{Method: t.Base, Qualifiers: mergeQualifiers(a.Qualifiers, t.Qualifiers), RefQualifier: a.RefQualifier}
  2065. }
  2066. case *TypeWithQualifiers:
  2067. if ft, ok := a.Base.(*FunctionType); ok {
  2068. return &MethodWithQualifiers{Method: ft, Qualifiers: a.Qualifiers, RefQualifier: ""}
  2069. }
  2070. if t, ok := a.Base.(*TypeWithQualifiers); ok {
  2071. return &TypeWithQualifiers{Base: t.Base, Qualifiers: mergeQualifiers(a.Qualifiers, t.Qualifiers)}
  2072. }
  2073. if m, ok := a.Base.(*MethodWithQualifiers); ok {
  2074. return &MethodWithQualifiers{Method: m.Method, Qualifiers: mergeQualifiers(a.Qualifiers, m.Qualifiers), RefQualifier: m.RefQualifier}
  2075. }
  2076. case *ReferenceType:
  2077. if rt, ok := a.Base.(*ReferenceType); ok {
  2078. return rt
  2079. }
  2080. if rrt, ok := a.Base.(*RvalueReferenceType); ok {
  2081. return &ReferenceType{Base: rrt.Base}
  2082. }
  2083. case *RvalueReferenceType:
  2084. if rrt, ok := a.Base.(*RvalueReferenceType); ok {
  2085. return rrt
  2086. }
  2087. if rt, ok := a.Base.(*ReferenceType); ok {
  2088. return rt
  2089. }
  2090. case *ArrayType:
  2091. // Qualifiers on the element of an array type
  2092. // go on the whole array type.
  2093. if q, ok := a.Element.(*TypeWithQualifiers); ok {
  2094. return &TypeWithQualifiers{
  2095. Base: &ArrayType{Dimension: a.Dimension, Element: q.Base},
  2096. Qualifiers: q.Qualifiers,
  2097. }
  2098. }
  2099. case *PackExpansion:
  2100. // Expand the pack and replace it with a list of
  2101. // expressions.
  2102. if a.Pack != nil {
  2103. exprs := make([]AST, len(a.Pack.Args))
  2104. for i, arg := range a.Pack.Args {
  2105. copy := func(sub AST) AST {
  2106. // Replace the ArgumentPack
  2107. // with a specific argument.
  2108. if sub == a.Pack {
  2109. return arg
  2110. }
  2111. // Copy everything else.
  2112. return nil
  2113. }
  2114. skip := func(sub AST) bool {
  2115. // Don't traverse into another
  2116. // pack expansion.
  2117. _, skip := sub.(*PackExpansion)
  2118. return skip
  2119. }
  2120. exprs[i] = simplify(a.Base.Copy(copy, skip))
  2121. }
  2122. return &ExprList{Exprs: exprs}
  2123. }
  2124. }
  2125. return nil
  2126. }
  2127. // findArgumentPack walks the AST looking for the argument pack for a
  2128. // pack expansion. We find it via a template parameter.
  2129. func (st *state) findArgumentPack(a AST) *ArgumentPack {
  2130. var ret *ArgumentPack
  2131. a.Traverse(func(a AST) bool {
  2132. if ret != nil {
  2133. return false
  2134. }
  2135. switch a := a.(type) {
  2136. case *TemplateParam:
  2137. if a.Template == nil || a.Index >= len(a.Template.Args) {
  2138. return true
  2139. }
  2140. if pack, ok := a.Template.Args[a.Index].(*ArgumentPack); ok {
  2141. ret = pack
  2142. return false
  2143. }
  2144. case *PackExpansion, *Closure, *Name:
  2145. return false
  2146. case *TaggedName, *Operator, *BuiltinType, *FunctionParam:
  2147. return false
  2148. case *UnnamedType, *FixedType, *DefaultArg:
  2149. return false
  2150. }
  2151. return true
  2152. })
  2153. return ret
  2154. }