Compiler-Interpreter.st 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. Smalltalk current createPackage: 'Compiler-Interpreter' properties: #{}!
  2. NodeVisitor subclass: #ASTInterpreter
  3. instanceVariableNames: 'currentNode context shouldReturn'
  4. package: 'Compiler-Interpreter'!
  5. !ASTInterpreter methodsFor: 'accessing'!
  6. context
  7. ^ context
  8. !
  9. context: aMethodContext
  10. context := aMethodContext
  11. ! !
  12. !ASTInterpreter methodsFor: 'initialization'!
  13. initialize
  14. super initialize.
  15. shouldReturn := false
  16. ! !
  17. !ASTInterpreter methodsFor: 'interpreting'!
  18. blockValue: anASTBlockClosure
  19. ^ self interpret: anASTBlockClosure astNode nodes first
  20. !
  21. interpret: aNode
  22. shouldReturn := false.
  23. ^ self interpretNode: aNode
  24. !
  25. interpretNode: aNode
  26. currentNode := aNode.
  27. ^ self visit: aNode
  28. !
  29. send: aSelector to: anObject arguments: aCollection
  30. ^ anObject perform: aSelector withArguments: aCollection
  31. ! !
  32. !ASTInterpreter methodsFor: 'visiting'!
  33. visitBlockNode: aNode
  34. ^ [ self interpretNode: aNode nodes first ]
  35. !
  36. visitReturnNode: aNode
  37. shouldReturn := true.
  38. ^ self interpretNode: aNode nodes first
  39. !
  40. visitSendNode: aNode
  41. "TODO: Handle super sends"
  42. | receiver arguments |
  43. receiver := self interpretNode: aNode receiver.
  44. arguments := aNode arguments collect: [ :each |
  45. self interpretNode: each ].
  46. ^ self send: aNode selector to: receiver arguments: arguments
  47. !
  48. visitSequenceNode: aNode
  49. aNode nodes allButLast do: [ :each | | value |
  50. value := self interpretNode: each.
  51. shouldReturn ifTrue: [ ^ value ] ].
  52. ^ self interpretNode: aNode nodes last
  53. !
  54. visitValueNode: aNode
  55. ^ aNode value
  56. ! !
  57. TestCase subclass: #ASTInterpretorTest
  58. instanceVariableNames: ''
  59. package: 'Compiler-Interpreter'!
  60. !ASTInterpretorTest methodsFor: 'accessing'!
  61. analyze: aNode forClass: aClass
  62. (SemanticAnalyzer on: aClass) visit: aNode.
  63. ^ aNode
  64. !
  65. interpret: aString
  66. "the food is a methodNode. Interpret the sequenceNode only"
  67. ^ ASTInterpreter new
  68. interpret: (self parse: aString forClass: Object)
  69. nodes first
  70. !
  71. parse: aString
  72. ^ Smalltalk current parse: aString
  73. !
  74. parse: aString forClass: aClass
  75. ^ self analyze: (self parse: aString) forClass: aClass
  76. ! !
  77. !ASTInterpretorTest methodsFor: 'tests'!
  78. testBinarySend
  79. self assert: (self interpret: 'foo 2+3+4') equals: 9
  80. !
  81. testBlockLiteral
  82. self assert: false
  83. ! !