expressions.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. package zygo
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strconv"
  6. "strings"
  7. )
  8. // all Sexp are typed, and have a zero value corresponding to
  9. // the type of the Sexp.
  10. // Sexp is the central interface for all
  11. // S-expressions (Symbol expressions ala lisp).
  12. type Sexp interface {
  13. // SexpString: produce a string from our value.
  14. // Single-line strings can ignore indent.
  15. // Only multiline strings should follow every
  16. // newline with at least indent worth of spaces.
  17. SexpString(ps *PrintState) string
  18. // Type returns the type of the value.
  19. Type() *RegisteredType
  20. }
  21. type SexpPair struct {
  22. Head Sexp
  23. Tail Sexp
  24. }
  25. type SexpPointer struct {
  26. ReflectTarget reflect.Value
  27. Target Sexp
  28. PointedToType *RegisteredType
  29. MyType *RegisteredType
  30. }
  31. func NewSexpPointer(pointedTo Sexp) *SexpPointer {
  32. pointedToType := pointedTo.Type()
  33. var reftarg reflect.Value
  34. //Q("NewSexpPointer sees pointedTo of '%#v'", pointedTo)
  35. switch e := pointedTo.(type) {
  36. case *SexpReflect:
  37. //Q("SexpReflect.Val = '%#v'", e.Val)
  38. reftarg = e.Val
  39. default:
  40. reftarg = reflect.ValueOf(pointedTo)
  41. }
  42. ptrRt := GoStructRegistry.GetOrCreatePointerType(pointedToType)
  43. //Q("pointer type is ptrRt = '%#v'", ptrRt)
  44. p := &SexpPointer{
  45. ReflectTarget: reftarg,
  46. Target: pointedTo,
  47. PointedToType: pointedToType,
  48. MyType: ptrRt,
  49. }
  50. return p
  51. }
  52. func (p *SexpPointer) SexpString(ps *PrintState) string {
  53. return fmt.Sprintf("%p", &p.Target)
  54. //return fmt.Sprintf("(* %v) %p", p.PointedToType.RegisteredName, p.Target)
  55. }
  56. func (p *SexpPointer) Type() *RegisteredType {
  57. return p.MyType
  58. }
  59. type SexpInt struct {
  60. Val int64
  61. Typ *RegisteredType
  62. }
  63. type SexpUint64 struct {
  64. Val uint64
  65. Typ *RegisteredType
  66. }
  67. type SexpBool struct {
  68. Val bool
  69. Typ *RegisteredType
  70. }
  71. type SexpFloat struct {
  72. Val float64
  73. Typ *RegisteredType
  74. Scientific bool
  75. }
  76. type SexpChar struct {
  77. Val rune
  78. Typ *RegisteredType
  79. }
  80. type SexpStr struct {
  81. S string
  82. backtick bool
  83. Typ *RegisteredType
  84. }
  85. func (r SexpStr) Type() *RegisteredType {
  86. return GoStructRegistry.Registry["string"]
  87. }
  88. func (r *SexpInt) Type() *RegisteredType {
  89. return GoStructRegistry.Registry["int64"]
  90. }
  91. func (r *SexpUint64) Type() *RegisteredType {
  92. return GoStructRegistry.Registry["uint64"]
  93. }
  94. func (r *SexpFloat) Type() *RegisteredType {
  95. return GoStructRegistry.Registry["float64"]
  96. }
  97. func (r *SexpBool) Type() *RegisteredType {
  98. return GoStructRegistry.Registry["bool"]
  99. }
  100. func (r *SexpChar) Type() *RegisteredType {
  101. return GoStructRegistry.Registry["int32"]
  102. }
  103. func (r *RegisteredType) Type() *RegisteredType {
  104. return r
  105. }
  106. type SexpRaw struct {
  107. Val []byte
  108. Typ *RegisteredType
  109. }
  110. func (r *SexpRaw) Type() *RegisteredType {
  111. return r.Typ
  112. }
  113. type SexpReflect struct {
  114. Val reflect.Value
  115. }
  116. func (r *SexpReflect) Type() *RegisteredType {
  117. k := reflectName(reflect.Value(r.Val))
  118. //Q("SexpReflect.Type() looking up type named '%s'", k)
  119. ty, ok := GoStructRegistry.Registry[k]
  120. if !ok {
  121. //Q("SexpReflect.Type(): type named '%s' not found", k)
  122. return nil
  123. }
  124. //Q("SexpReflect.Type(): type named '%s' found as regtype '%v'", k, ty.SexpString(nil))
  125. return ty
  126. }
  127. type SexpError struct {
  128. error
  129. }
  130. func (r *SexpError) Type() *RegisteredType {
  131. return GoStructRegistry.Registry["error"]
  132. }
  133. func (r *SexpSentinel) Type() *RegisteredType {
  134. return nil // TODO what should this be?
  135. }
  136. type SexpClosureEnv Scope
  137. func (r *SexpClosureEnv) Type() *RegisteredType {
  138. return nil // TODO what should this be?
  139. }
  140. func (c *SexpClosureEnv) SexpString(ps *PrintState) string {
  141. scop := (*Scope)(c)
  142. s, err := scop.Show(scop.env, ps, "")
  143. if err != nil {
  144. panic(err)
  145. }
  146. return s
  147. }
  148. type SexpSentinel struct {
  149. Val int
  150. }
  151. // these are values now so that they also have addresses.
  152. var SexpNull = &SexpSentinel{Val: 0}
  153. var SexpEnd = &SexpSentinel{Val: 1}
  154. var SexpMarker = &SexpSentinel{Val: 2}
  155. type SexpSemicolon struct{}
  156. type SexpComma struct{}
  157. func (r *SexpSemicolon) Type() *RegisteredType {
  158. return nil // TODO what should this be?
  159. }
  160. func (s *SexpSemicolon) SexpString(ps *PrintState) string {
  161. return ";"
  162. }
  163. func (r *SexpComma) Type() *RegisteredType {
  164. return nil // TODO what should this be?
  165. }
  166. func (s *SexpComma) SexpString(ps *PrintState) string {
  167. return ","
  168. }
  169. func (sent *SexpSentinel) SexpString(ps *PrintState) string {
  170. if sent == SexpNull {
  171. return "nil"
  172. }
  173. if sent == SexpEnd {
  174. return "End"
  175. }
  176. if sent == SexpMarker {
  177. return "Marker"
  178. }
  179. return ""
  180. }
  181. func Cons(a Sexp, b Sexp) *SexpPair {
  182. return &SexpPair{a, b}
  183. }
  184. func (pair *SexpPair) SexpString(ps *PrintState) string {
  185. str := "("
  186. for {
  187. switch pair.Tail.(type) {
  188. case *SexpPair:
  189. str += pair.Head.SexpString(ps) + " "
  190. pair = pair.Tail.(*SexpPair)
  191. continue
  192. }
  193. break
  194. }
  195. str += pair.Head.SexpString(ps)
  196. if pair.Tail == SexpNull {
  197. str += ")"
  198. } else {
  199. str += " \\ " + pair.Tail.SexpString(ps) + ")"
  200. }
  201. return str
  202. }
  203. func (r *SexpPair) Type() *RegisteredType {
  204. return nil // TODO what should this be?
  205. }
  206. type SexpArray struct {
  207. Val []Sexp
  208. Typ *RegisteredType
  209. IsFuncDeclTypeArray bool
  210. Infix bool
  211. Env *Zlisp
  212. }
  213. func (r *SexpArray) Type() *RegisteredType {
  214. if r.Typ == nil {
  215. if len(r.Val) > 0 {
  216. // take type from first element
  217. ty := r.Val[0].Type()
  218. if ty != nil {
  219. r.Typ = GoStructRegistry.GetOrCreateSliceType(ty)
  220. }
  221. } else {
  222. // empty array
  223. r.Typ = GoStructRegistry.Lookup("[]")
  224. //P("lookup [] returned type %#v", r.Typ)
  225. }
  226. }
  227. return r.Typ
  228. }
  229. func (arr *SexpArray) SexpString(ps *PrintState) string {
  230. indInner := ""
  231. indent := ps.GetIndent()
  232. innerPs := ps.AddIndent(4) // generates a fresh new PrintState
  233. inner := indent + 4
  234. //prettyEnd := ""
  235. pretty := false
  236. if arr != nil && arr.Env != nil && arr.Env.Pretty {
  237. pretty = true
  238. //prettyEnd = "\n"
  239. indInner = strings.Repeat(" ", inner)
  240. ps = innerPs
  241. }
  242. opn := "["
  243. cls := "]"
  244. if arr.Infix {
  245. opn = "{"
  246. cls = "}"
  247. }
  248. if pretty {
  249. opn += "\n"
  250. indInner = strings.Repeat(" ", inner)
  251. }
  252. if len(arr.Val) == 0 {
  253. return opn + cls
  254. }
  255. ta := arr.IsFuncDeclTypeArray
  256. str := opn
  257. for i, sexp := range arr.Val {
  258. str += indInner + sexp.SexpString(ps)
  259. if ta && i%2 == 0 {
  260. str += ":"
  261. } else {
  262. str += " "
  263. }
  264. }
  265. m := len(str)
  266. str = str[:m-1] + indInner + cls
  267. return str
  268. }
  269. func (e *SexpError) SexpString(ps *PrintState) string {
  270. return e.error.Error()
  271. }
  272. type EmbedPath struct {
  273. ChildName string
  274. ChildFieldNum int
  275. }
  276. func GetEmbedPath(e []EmbedPath) string {
  277. r := ""
  278. last := len(e) - 1
  279. for i, s := range e {
  280. r += s.ChildName
  281. if i < last {
  282. r += ":"
  283. }
  284. }
  285. return r
  286. }
  287. type HashFieldDet struct {
  288. FieldNum int
  289. FieldType reflect.Type
  290. StructField reflect.StructField
  291. FieldName string
  292. FieldJsonTag string
  293. EmbedPath []EmbedPath // we are embedded if len(EmbedPath) > 0
  294. }
  295. type SexpHash struct {
  296. TypeName string
  297. Map map[int][]*SexpPair
  298. KeyOrder []Sexp
  299. GoStructFactory *RegisteredType
  300. NumKeys int
  301. GoMethods []reflect.Method
  302. GoFields []reflect.StructField
  303. GoMethSx SexpArray
  304. GoFieldSx SexpArray
  305. GoType reflect.Type
  306. NumMethod int
  307. GoShadowStruct interface{}
  308. GoShadowStructVa reflect.Value
  309. ShadowSet bool
  310. // json tag name -> pointers to example values, as factories for SexpToGoStructs()
  311. JsonTagMap map[string]*HashFieldDet
  312. DetOrder []*HashFieldDet
  313. // for using these as a scoping model
  314. DefnEnv *SexpHash
  315. SuperClass *SexpHash
  316. ZMain SexpFunction
  317. ZMethods map[string]*SexpFunction
  318. Env *Zlisp
  319. }
  320. var MethodNotFound = fmt.Errorf("method not found")
  321. func (h *SexpHash) RunZmethod(method string, args []Sexp) (Sexp, error) {
  322. f, ok := (h.ZMethods)[method]
  323. if !ok {
  324. return SexpNull, MethodNotFound
  325. }
  326. panic(fmt.Errorf("not done calling %s", f.name))
  327. //return SexpNull, nil
  328. }
  329. func CallZMethodOnRecordFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
  330. narg := len(args)
  331. if narg < 2 {
  332. return SexpNull, WrongNargs
  333. }
  334. var hash *SexpHash
  335. switch h := args[0].(type) {
  336. case *SexpHash:
  337. hash = h
  338. default:
  339. return SexpNull, fmt.Errorf("can only _call on a record")
  340. }
  341. method := ""
  342. switch s := args[1].(type) {
  343. case *SexpSymbol:
  344. method = s.name
  345. case *SexpStr:
  346. method = s.S
  347. default:
  348. return SexpNull, fmt.Errorf("can only _call with a " +
  349. "symbol or string as the method name. example: (_call record method:)")
  350. }
  351. return hash.RunZmethod(method, args[2:])
  352. }
  353. func (h *SexpHash) SetMain(p *SexpFunction) {
  354. h.BindSymbol(h.Env.MakeSymbol(".main"), p)
  355. }
  356. func (h *SexpHash) SetDefnEnv(p *SexpHash) {
  357. h.DefnEnv = p
  358. h.BindSymbol(h.Env.MakeSymbol(".parent"), p)
  359. }
  360. func (h *SexpHash) Lookup(env *Zlisp, key Sexp) (expr Sexp, err error) {
  361. return h.HashGet(env, key)
  362. }
  363. func (h *SexpHash) BindSymbol(key *SexpSymbol, val Sexp) error {
  364. return h.HashSet(key, val)
  365. }
  366. func (h *SexpHash) SetGoStructFactory(factory *RegisteredType) {
  367. h.GoStructFactory = factory
  368. }
  369. var SexpIntSize = 64
  370. var SexpFloatSize = 64
  371. func (r *SexpReflect) SexpString(ps *PrintState) string {
  372. //Q("in SexpReflect.SexpString(indent); top; type = %T", r)
  373. if reflect.Value(r.Val).Type().Kind() == reflect.Ptr {
  374. iface := reflect.Value(r.Val).Interface()
  375. switch iface.(type) {
  376. case *string:
  377. return fmt.Sprintf("`%v`", reflect.Value(r.Val).Elem().Interface())
  378. default:
  379. return fmt.Sprintf("%v", reflect.Value(r.Val).Elem().Interface())
  380. }
  381. }
  382. iface := reflect.Value(r.Val).Interface()
  383. //Q("in SexpReflect.SexpString(indent); type = %T", iface)
  384. switch iface.(type) {
  385. default:
  386. return fmt.Sprintf("%v", iface)
  387. }
  388. }
  389. func (b *SexpBool) SexpString(ps *PrintState) string {
  390. if bool(b.Val) {
  391. return "true"
  392. }
  393. return "false"
  394. }
  395. func (i *SexpInt) SexpString(ps *PrintState) string {
  396. return strconv.Itoa(int(i.Val))
  397. }
  398. func (i *SexpUint64) SexpString(ps *PrintState) string {
  399. return strconv.FormatUint(i.Val, 10) + "ULL"
  400. }
  401. func (f *SexpFloat) SexpString(ps *PrintState) string {
  402. if f.Scientific {
  403. return strconv.FormatFloat(f.Val, 'e', -1, SexpFloatSize)
  404. }
  405. return strconv.FormatFloat(f.Val, 'f', -1, SexpFloatSize)
  406. }
  407. func (c *SexpChar) SexpString(ps *PrintState) string {
  408. return strconv.QuoteRune(c.Val)
  409. }
  410. func (s *SexpStr) SexpString(ps *PrintState) string {
  411. if s.backtick {
  412. return "`" + s.S + "`"
  413. }
  414. return strconv.Quote(string(s.S))
  415. }
  416. func (r *SexpRaw) SexpString(ps *PrintState) string {
  417. return fmt.Sprintf("%#v", []byte(r.Val))
  418. }
  419. type SexpSymbol struct {
  420. name string
  421. number int
  422. isDot bool
  423. isSigil bool
  424. colonTail bool
  425. sigil string
  426. }
  427. func (sym *SexpSymbol) RHS(env *Zlisp) (Sexp, error) {
  428. if sym.isDot && env != nil {
  429. return dotGetSetHelper(env, sym.name, nil)
  430. }
  431. return sym, nil
  432. }
  433. func (sym *SexpSymbol) AssignToSelection(env *Zlisp, rhs Sexp) error {
  434. if sym.isDot && env != nil {
  435. _, err := dotGetSetHelper(env, sym.name, &rhs)
  436. return err
  437. }
  438. panic("not implemented yet")
  439. }
  440. func (sym *SexpSymbol) SexpString(ps *PrintState) string {
  441. if sym.colonTail {
  442. // return sym.name + ":"
  443. }
  444. return sym.name
  445. }
  446. func (r *SexpSymbol) Type() *RegisteredType {
  447. return GoStructRegistry.Registry["symbol"]
  448. }
  449. func (sym SexpSymbol) Name() string {
  450. return sym.name
  451. }
  452. func (sym SexpSymbol) Number() int {
  453. return sym.number
  454. }
  455. // SexpInterfaceDecl
  456. type SexpInterfaceDecl struct {
  457. name string
  458. methods []*SexpFunction
  459. }
  460. func (r *SexpInterfaceDecl) SexpString(ps *PrintState) string {
  461. indent := ps.GetIndent()
  462. space := strings.Repeat(" ", indent)
  463. space4 := strings.Repeat(" ", indent+4)
  464. s := space + "(interface " + r.name + " ["
  465. if len(r.methods) > 0 {
  466. s += "\n"
  467. }
  468. for i := range r.methods {
  469. s += space4 + r.methods[i].SexpString(ps.AddIndent(4)) + "\n"
  470. }
  471. s += space + "])"
  472. return s
  473. }
  474. func (r *SexpInterfaceDecl) Type() *RegisteredType {
  475. // todo: how to register/what to register?
  476. return GoStructRegistry.Registry[r.name]
  477. }
  478. // SexpFunction
  479. type SexpFunction struct {
  480. name string
  481. user bool
  482. nargs int
  483. varargs bool
  484. fun ZlispFunction
  485. userfun ZlispUserFunction
  486. orig Sexp
  487. closingOverScopes *Closing
  488. parent *SexpFunction
  489. isBuilder bool // see defbuild; builders are builtins that receive un-evaluated expressions
  490. inputTypes *SexpHash
  491. returnTypes *SexpHash
  492. hasBody bool // could just be declaration in an interface, without a body
  493. }
  494. func (sf *SexpFunction) Type() *RegisteredType {
  495. return nil // TODO what goes here
  496. }
  497. func (sf *SexpFunction) Copy() *SexpFunction {
  498. cp := *sf
  499. return &cp
  500. }
  501. func (sf *SexpFunction) SetClosing(clos *Closing) {
  502. ps4 := NewPrintStateWithIndent(4)
  503. pre, err := sf.ShowClosing(clos.env, ps4, "prev")
  504. _ = pre
  505. panicOn(err)
  506. newnew, err := sf.ShowClosing(clos.env, ps4, "newnew")
  507. _ = newnew
  508. panicOn(err)
  509. //P("99999 for sfun = %p, in sfun.SetClosing(), prev value is %p = '%s'\n",
  510. // sf, sf.closingOverScopes, pre)
  511. //P("88888 in sfun.SetClosing(), new value is %p = '%s'\n", clos, newnew)
  512. sf.closingOverScopes = clos
  513. //P("in SetClosing() for '%s'/%p: my stack is: '%s'", sf.name, sf, clos.Stack.SexpString(nil))
  514. }
  515. func (sf *SexpFunction) ShowClosing(env *Zlisp, ps *PrintState, label string) (string, error) {
  516. if sf.closingOverScopes == nil {
  517. return sf.name + " has no captured scopes.", nil
  518. }
  519. return sf.closingOverScopes.Show(env, ps, label)
  520. }
  521. func (sf *SexpFunction) ClosingLookupSymbolUntilFunction(sym *SexpSymbol) (Sexp, error, *Scope) {
  522. if sf.closingOverScopes != nil {
  523. return sf.closingOverScopes.LookupSymbolUntilFunction(sym, nil, 1, false)
  524. }
  525. return SexpNull, SymNotFound, nil
  526. }
  527. func (sf *SexpFunction) ClosingLookupSymbol(sym *SexpSymbol, setVal *Sexp) (Sexp, error, *Scope) {
  528. if sf.closingOverScopes != nil {
  529. return sf.closingOverScopes.LookupSymbol(sym, setVal)
  530. }
  531. //P("sf.closingOverScopes was nil, no captured scopes. sf = '%v'", sf.SexpString(nil))
  532. return SexpNull, SymNotFound, nil
  533. }
  534. // chase parent pointers up the chain and check each of their immediate closures.
  535. func (sf *SexpFunction) LookupSymbolInParentChainOfClosures(sym *SexpSymbol, setVal *Sexp, env *Zlisp) (Sexp, error, *Scope) {
  536. cur := sf
  537. par := sf.parent
  538. for par != nil {
  539. //fmt.Printf(" parent chain: cur:%v -> parent:%v\n", cur.name, par.name)
  540. //fmt.Printf(" cur.closures = %s", ClosureToString(cur, env))
  541. exp, err, scope := cur.ClosingLookupSymbolUntilFunc(sym, setVal, 1, false)
  542. if err == nil {
  543. //P("LookupSymbolInParentChainOfClosures(sym='%s') found in scope '%s'\n", sym.name, scope.Name)
  544. return exp, err, scope
  545. }
  546. cur = par
  547. par = par.parent
  548. }
  549. return SexpNull, SymNotFound, nil
  550. }
  551. func (sf *SexpFunction) ClosingLookupSymbolUntilFunc(sym *SexpSymbol, setVal *Sexp, maximumFuncToSearch int, checkCaptures bool) (Sexp, error, *Scope) {
  552. if sf.closingOverScopes != nil {
  553. return sf.closingOverScopes.LookupSymbolUntilFunction(sym, setVal, maximumFuncToSearch, checkCaptures)
  554. }
  555. //P("sf.closingOverScopes was nil, no captured scopes. sf = '%v'", sf.SexpString(nil))
  556. return SexpNull, SymNotFound, nil
  557. }
  558. func (sf *SexpFunction) SexpString(ps *PrintState) string {
  559. if sf.orig == nil {
  560. return "fn [" + sf.name + "]"
  561. }
  562. return sf.orig.SexpString(ps)
  563. }
  564. func IsTruthy(expr Sexp) bool {
  565. switch e := expr.(type) {
  566. case *SexpBool:
  567. return e.Val
  568. case *SexpInt:
  569. return e.Val != 0
  570. case *SexpUint64:
  571. return e.Val != 0
  572. case *SexpChar:
  573. return e.Val != 0
  574. case *SexpSentinel:
  575. return e != SexpNull
  576. }
  577. return true
  578. }
  579. type SexpStackmark struct {
  580. sym *SexpSymbol
  581. }
  582. func (r *SexpStackmark) Type() *RegisteredType {
  583. return nil // TODO what should this be?
  584. }
  585. func (mark *SexpStackmark) SexpString(ps *PrintState) string {
  586. return "stackmark " + mark.sym.name
  587. }