1
0

Compiler-Interpreter.st 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. Smalltalk current createPackage: 'Compiler-Interpreter'!
  2. BlockClosure subclass: #AIBlockClosure
  3. instanceVariableNames: 'node outerContext'
  4. package: 'Compiler-Interpreter'!
  5. !AIBlockClosure commentStamp!
  6. I am a special `BlockClosure` subclass used by an interpreter to interpret a block node.
  7. While I am polymorphic with `BlockClosure`, some methods such as `#new` will raise interpretation errors. Unlike a `BlockClosure`, my instance are not JavaScript functions.
  8. Evaluating an instance will result in interpreting the `node` instance variable (instance of `BlockNode`).!
  9. !AIBlockClosure methodsFor: 'accessing'!
  10. compiledSource
  11. "Unlike blocks, the receiver doesn't represent a JS function"
  12. ^ '[ AST Block closure ]'
  13. !
  14. numArgs
  15. ^ node temps size
  16. ! !
  17. !AIBlockClosure methodsFor: 'converting'!
  18. currySelf
  19. self interpreterError
  20. ! !
  21. !AIBlockClosure methodsFor: 'error handling'!
  22. interpreterError
  23. ASTInterpreterError signal: 'Method cannot be interpreted by the interpreter.'
  24. ! !
  25. !AIBlockClosure methodsFor: 'evaluating'!
  26. applyTo: anObject arguments: aCollection
  27. self interpreterError
  28. !
  29. value
  30. ^ self valueWithPossibleArguments: #()
  31. !
  32. value: anArgument
  33. ^ self valueWithPossibleArguments: {anArgument}
  34. !
  35. value: firstArgument value: secondArgument
  36. ^ self valueWithPossibleArguments: {firstArgument . secondArgument}
  37. !
  38. value: firstArgument value: secondArgument value: thirdArgument
  39. ^ self valueWithPossibleArguments: {firstArgument . secondArgument . thirdArgument}
  40. !
  41. valueWithPossibleArguments: aCollection
  42. | context sequenceNode |
  43. context := outerContext newBlockContext.
  44. "Interpret a copy of the sequence node to avoid creating a new AIBlockClosure"
  45. sequenceNode := node nodes first copy
  46. parent: nil;
  47. yourself.
  48. "Populate the arguments into the context locals"
  49. node parameters withIndexDo: [ :each :index |
  50. context localAt: each put: (aCollection at: index ifAbsent: [ nil ]) ].
  51. "Interpret the first node of the BlockSequenceNode"
  52. context interpreter
  53. node: sequenceNode nextChild;
  54. proceed.
  55. outerContext interpreter
  56. setNonLocalReturnFromContext: context.
  57. ^ context interpreter pop
  58. ! !
  59. !AIBlockClosure methodsFor: 'initialization'!
  60. initializeWithContext: aContext node: aNode
  61. node := aNode.
  62. outerContext := aContext
  63. ! !
  64. !AIBlockClosure class methodsFor: 'instance creation'!
  65. forContext: aContext node: aNode
  66. ^ self new
  67. initializeWithContext: aContext node: aNode;
  68. yourself
  69. ! !
  70. MethodContext subclass: #AIContext
  71. instanceVariableNames: 'outerContext innerContext pc locals selector index ast interpreter'
  72. package: 'Compiler-Interpreter'!
  73. !AIContext commentStamp!
  74. I am like a `MethodContext`, used by the `ASTInterpreter`.
  75. Unlike a `MethodContext`, my instances are not read-only.
  76. When debugging, my instances are created by copying the current `MethodContext` (thisContext)!
  77. !AIContext methodsFor: 'accessing'!
  78. index
  79. ^ index ifNil: [ 0 ]
  80. !
  81. index: anInteger
  82. index := anInteger
  83. !
  84. innerContext
  85. ^ innerContext
  86. !
  87. innerContext: anAIContext
  88. innerContext := anAIContext
  89. !
  90. localAt: aString
  91. "Lookup the local value up to the method context"
  92. ^ self locals at: aString ifAbsent: [
  93. self outerContext ifNotNil: [ :context |
  94. context localAt: aString ] ]
  95. !
  96. localAt: aString ifAbsent: aBlock
  97. "Lookup the local value up to the method context"
  98. ^ self locals at: aString ifAbsent: [
  99. self outerContext
  100. ifNotNil: [ :context | context localAt: aString ifAbsent: aBlock ]
  101. ifNil: [aBlock value] ]
  102. !
  103. localAt: aString put: anObject
  104. self locals at: aString put: anObject
  105. !
  106. locals
  107. locals ifNil: [ self initializeLocals ].
  108. ^ locals
  109. !
  110. method
  111. ^ self methodContext ifNotNil: [
  112. self methodContext receiver class lookupSelector: self methodContext selector ]
  113. !
  114. outerContext
  115. ^ outerContext
  116. !
  117. outerContext: anAIContext
  118. outerContext := anAIContext.
  119. outerContext innerContext: self
  120. !
  121. selector
  122. ^ selector
  123. !
  124. selector: aString
  125. selector := aString
  126. ! !
  127. !AIContext methodsFor: 'factory'!
  128. newBlockContext
  129. ^ self class new
  130. outerContext: self;
  131. yourself
  132. ! !
  133. !AIContext methodsFor: 'initialization'!
  134. initializeAST
  135. ast := self method ast.
  136. (SemanticAnalyzer on: self method methodClass)
  137. visit: ast
  138. !
  139. initializeFromMethodContext: aMethodContext
  140. self
  141. pc: aMethodContext pc;
  142. index: aMethodContext index;
  143. receiver: aMethodContext receiver;
  144. selector: aMethodContext selector.
  145. aMethodContext outerContext ifNotNil: [ :outer |
  146. "If the method context is nil, the block was defined in JS, so ignore it"
  147. outer methodContext ifNotNil: [
  148. self outerContext: (self class fromMethodContext: aMethodContext outerContext) ].
  149. aMethodContext locals keysAndValuesDo: [ :key :value |
  150. self locals at: key put: value ] ]
  151. !
  152. initializeInterpreter
  153. interpreter := ASTInterpreter new
  154. context: self;
  155. node: self retrieveNode;
  156. yourself.
  157. (self innerContext notNil and: [
  158. self innerContext isBlockContext not ]) ifTrue: [
  159. self setupInterpreter: interpreter ]
  160. !
  161. initializeLocals
  162. locals := Dictionary new.
  163. locals at: 'thisContext' put: self.
  164. ! !
  165. !AIContext methodsFor: 'interpreting'!
  166. arguments
  167. ^ self ast arguments collect: [ :each |
  168. self localAt: each ]
  169. !
  170. ast
  171. self isBlockContext ifTrue: [
  172. ^ self outerContext ifNotNil: [ :context | context ast ] ].
  173. ast ifNil: [ self initializeAST ].
  174. ^ ast
  175. !
  176. interpreter
  177. interpreter ifNil: [ self initializeInterpreter ].
  178. ^ interpreter
  179. !
  180. interpreter: anInterpreter
  181. interpreter := anInterpreter
  182. !
  183. pc
  184. ^ pc ifNil: [ pc := 0 ]
  185. !
  186. pc: anInteger
  187. pc := anInteger
  188. !
  189. receiver
  190. ^ self localAt: 'self'
  191. !
  192. receiver: anObject
  193. self localAt: 'self' put: anObject
  194. !
  195. retrieveNode
  196. ^ self ast ifNotNil: [
  197. ASTPCNodeVisitor new
  198. context: self;
  199. visit: self ast;
  200. currentNode ]
  201. !
  202. setupInterpreter: anInterpreter
  203. "Push the send args and receiver to the interpreter stack"
  204. self innerContext arguments reversed do: [ :each |
  205. anInterpreter push: each ].
  206. anInterpreter push: (self innerContext receiver)
  207. ! !
  208. !AIContext class methodsFor: 'instance creation'!
  209. fromMethodContext: aMethodContext
  210. ^ self new
  211. initializeFromMethodContext: aMethodContext;
  212. yourself
  213. ! !
  214. Object subclass: #ASTDebugger
  215. instanceVariableNames: 'interpreter context'
  216. package: 'Compiler-Interpreter'!
  217. !ASTDebugger commentStamp!
  218. I am a stepping debugger interface for Amber code.
  219. I internally use an instance of `ASTSteppingInterpreter` to actually step through node and interpret them.
  220. My instances are created from a `MethodContext` with `ASTDebugger class >> context:`.
  221. They hold an `AIContext` instance internally, recursive copy of the `MethodContext`.
  222. ## API
  223. Use the methods of the `'stepping'` protocol to do stepping.!
  224. !ASTDebugger methodsFor: 'accessing'!
  225. context
  226. ^ context
  227. !
  228. context: aContext
  229. context := aContext
  230. !
  231. interpreter
  232. ^ interpreter ifNil: [ interpreter := self defaultInterpreterClass new ]
  233. !
  234. interpreter: anInterpreter
  235. interpreter := anInterpreter
  236. !
  237. method
  238. ^ self context method
  239. !
  240. nextNode
  241. ^ self interpreter nextNode
  242. ! !
  243. !ASTDebugger methodsFor: 'defaults'!
  244. defaultInterpreterClass
  245. ^ ASTInterpreter
  246. ! !
  247. !ASTDebugger methodsFor: 'initialization'!
  248. buildAST
  249. "Build the AST tree from the method source code.
  250. The AST is annotated with a SemanticAnalyzer,
  251. to know the semantics and bindings of each node needed for later debugging"
  252. | ast |
  253. ast := Smalltalk current parse: self method source.
  254. (SemanticAnalyzer on: self context receiver class)
  255. visit: ast.
  256. ^ ast
  257. !
  258. initializeInterpreter
  259. | ast next |
  260. ast := self buildAST.
  261. next := ASTPCNodeVisitor new
  262. context: self context;
  263. visit: ast;
  264. currentNode.
  265. self interpreter node: next
  266. !
  267. initializeWithContext: aContext
  268. "TODO: do we need to handle block contexts?"
  269. self context: aContext.
  270. self initializeInterpreter
  271. ! !
  272. !ASTDebugger methodsFor: 'stepping'!
  273. proceed
  274. self shouldBeImplemented
  275. !
  276. restart
  277. self interpreter restart
  278. !
  279. stepInto
  280. self shouldBeImplemented
  281. !
  282. stepOver
  283. self interpreter stepOver
  284. ! !
  285. !ASTDebugger methodsFor: 'testing'!
  286. atEnd
  287. ^ self interpreter atEnd
  288. ! !
  289. !ASTDebugger class methodsFor: 'instance creation'!
  290. context: aContext
  291. ^ self new
  292. initializeWithContext: aContext;
  293. yourself
  294. ! !
  295. NodeVisitor subclass: #ASTInterpreter
  296. instanceVariableNames: 'node context stack returnValue returned'
  297. package: 'Compiler-Interpreter'!
  298. !ASTInterpreter commentStamp!
  299. I visit an AST, interpreting (evaluating) nodes one after the other, using a small stack machine.
  300. ## API
  301. While my instances should be used from within an `ASTDebugger`, which provides a more high level interface,
  302. you can use methods from the `interpreting` protocol:
  303. - `#step` evaluates the current `node` only
  304. - `#stepOver` evaluates the AST from the current `node` up to the next stepping node (most likely the next send node)
  305. - `#proceed` evaluates eagerly the AST
  306. - `#restart` select the first node of the AST
  307. - `#skip` skips the current node, moving to the next one if any!
  308. !ASTInterpreter methodsFor: 'accessing'!
  309. context
  310. ^ context
  311. !
  312. context: aContext
  313. context := aContext
  314. !
  315. node
  316. "Answer the next node, ie the node to be evaluated in the next step"
  317. ^ node
  318. !
  319. node: aNode
  320. node := aNode
  321. !
  322. result
  323. ^ self hasReturned
  324. ifTrue: [ self returnValue ]
  325. ifFalse: [ self context receiver ]
  326. !
  327. returnValue
  328. ^ returnValue
  329. !
  330. returnValue: anObject
  331. returnValue := anObject
  332. !
  333. stack
  334. ^ stack ifNil: [ stack := OrderedCollection new ]
  335. ! !
  336. !ASTInterpreter methodsFor: 'interpreting'!
  337. interpret
  338. "Interpret the next node to be evaluated"
  339. self visit: self node
  340. !
  341. interpret: aNode
  342. self node: aNode.
  343. self interpret
  344. !
  345. next
  346. self node: self node nextNode
  347. !
  348. proceed
  349. "Eagerly evaluate the ast"
  350. [ self atEnd ] whileFalse: [
  351. self step ]
  352. !
  353. restart
  354. self node: self context ast nextChild
  355. !
  356. setNonLocalReturnFromContext: aContext
  357. aContext interpreter hasReturned ifTrue: [
  358. returned := true.
  359. self returnValue: aContext interpreter returnValue ]
  360. !
  361. skip
  362. self next
  363. !
  364. step
  365. self
  366. interpret;
  367. next
  368. !
  369. stepOver
  370. self step.
  371. [ self node isSteppingNode ] whileFalse: [
  372. self step ]
  373. ! !
  374. !ASTInterpreter methodsFor: 'private'!
  375. assign: aNode to: anObject
  376. aNode binding isInstanceVar
  377. ifTrue: [ self context receiver instVarAt: aNode value put: anObject ]
  378. ifFalse: [ self context localAt: aNode value put: anObject ]
  379. !
  380. eval: aString
  381. "Evaluate aString as JS source inside an JS function.
  382. aString is not sandboxed."
  383. | source function |
  384. source := String streamContents: [ :str |
  385. str nextPutAll: '(function('.
  386. self context locals keys
  387. do: [ :each | str nextPutAll: each ]
  388. separatedBy: [ str nextPutAll: ',' ].
  389. str
  390. nextPutAll: '){ return (function() {';
  391. nextPutAll: aString;
  392. nextPutAll: '})() })' ].
  393. function := Compiler new eval: source.
  394. ^ function valueWithPossibleArguments: self context locals values
  395. !
  396. messageFromSendNode: aSendNode arguments: aCollection
  397. ^ Message new
  398. selector: aSendNode selector;
  399. arguments: aCollection;
  400. yourself
  401. !
  402. messageNotUnderstood: aMessage receiver: anObject
  403. MessageNotUnderstood new
  404. meesage: aMessage;
  405. receiver: anObject;
  406. signal
  407. !
  408. sendMessage: aMessage to: anObject superSend: aBoolean
  409. | method |
  410. aBoolean ifFalse: [ ^ aMessage sendTo: anObject ].
  411. anObject class superclass ifNil: [ ^ self messageNotUnderstood: aMessage receiver: anObject ].
  412. method := anObject class superclass methodDictionary
  413. at: aMessage selector
  414. ifAbsent: [ ^ self messageNotUnderstood: aMessage receiver: anObject ].
  415. ^ method sendTo: anObject arguments: aMessage arguments
  416. ! !
  417. !ASTInterpreter methodsFor: 'stack'!
  418. peek
  419. "Peek the top object of the context stack"
  420. self stack ifEmpty: [ ^ nil ].
  421. ^ self stack last
  422. !
  423. pop
  424. "Pop an object from the context stack"
  425. | peekedValue |
  426. peekedValue := self peek.
  427. self stack removeLast.
  428. ^ peekedValue
  429. !
  430. push: anObject
  431. "Push an object to the context stack"
  432. ^ self stack add: anObject
  433. ! !
  434. !ASTInterpreter methodsFor: 'testing'!
  435. atEnd
  436. ^ self hasReturned or: [ self node isNil ]
  437. !
  438. hasReturned
  439. ^ returned ifNil: [ false ]
  440. ! !
  441. !ASTInterpreter methodsFor: 'visiting'!
  442. visit: aNode
  443. self hasReturned ifFalse: [ super visit: aNode ]
  444. !
  445. visitAssignmentNode: aNode
  446. | poppedValue |
  447. poppedValue := self pop.
  448. "Pop the left side of the assignment.
  449. It already has been visited, and we don't need its value."
  450. self pop.
  451. self push: poppedValue.
  452. self assign: aNode left to: poppedValue
  453. !
  454. visitBlockNode: aNode
  455. "Do not evaluate the block node.
  456. Instead, put all instructions into a block that we push to the stack for later evaluation"
  457. | block |
  458. block := AIBlockClosure forContext: self context node: aNode.
  459. self push: block
  460. !
  461. visitDynamicArrayNode: aNode
  462. | array |
  463. array := #().
  464. aNode nodes do: [ :each |
  465. array addFirst: self pop ].
  466. self push: array
  467. !
  468. visitDynamicDictionaryNode: aNode
  469. | associations hashedCollection |
  470. associations := OrderedCollection new.
  471. hashedCollection := HashedCollection new.
  472. aNode nodes do: [ :each |
  473. associations add: self pop ].
  474. associations reversed do: [ :each |
  475. hashedCollection add: each ].
  476. self push: hashedCollection
  477. !
  478. visitJSStatementNode: aNode
  479. returned := true.
  480. self returnValue: (self eval: aNode source)
  481. !
  482. visitNode: aNode
  483. "Do nothing by default. Especially, do not visit children recursively."
  484. !
  485. visitReturnNode: aNode
  486. returned := true.
  487. self returnValue: self pop
  488. !
  489. visitSendNode: aNode
  490. | receiver args message result |
  491. args := aNode arguments collect: [ :each | self pop ].
  492. receiver := self pop.
  493. message := self
  494. messageFromSendNode: aNode
  495. arguments: args reversed.
  496. result := self sendMessage: message to: receiver superSend: aNode superSend.
  497. self context pc: self context pc + 1.
  498. "For cascade sends, push the reciever if the send is not the last one"
  499. (aNode isCascadeSendNode and: [ aNode isLastChild not ])
  500. ifTrue: [ self push: receiver ]
  501. ifFalse: [ self push: result ]
  502. !
  503. visitValueNode: aNode
  504. self push: aNode value
  505. !
  506. visitVariableNode: aNode
  507. aNode binding isUnknownVar ifTrue: [
  508. ^ self push: (PlatformInterface globals at: aNode value ifAbsent: [ self error: 'Unknown variable' ]) ].
  509. self push: (aNode binding isInstanceVar
  510. ifTrue: [ self context receiver instVarAt: aNode value ]
  511. ifFalse: [ self context
  512. localAt: aNode value
  513. ifAbsent: [
  514. aNode value isCapitalized
  515. ifTrue: [
  516. Smalltalk current
  517. at: aNode value
  518. ifAbsent: [ PlatformInterface globals at: aNode value ]]]])
  519. ! !
  520. Error subclass: #ASTInterpreterError
  521. instanceVariableNames: ''
  522. package: 'Compiler-Interpreter'!
  523. !ASTInterpreterError commentStamp!
  524. I get signaled when an AST interpreter is unable to interpret a node.!
  525. NodeVisitor subclass: #ASTPCNodeVisitor
  526. instanceVariableNames: 'useInlinings pc context blockIndex currentNode'
  527. package: 'Compiler-Interpreter'!
  528. !ASTPCNodeVisitor commentStamp!
  529. I visit an AST until I get to the current pc node and answer it.
  530. ## API
  531. My instances must be filled with a context object using `#context:`.
  532. After visiting the AST the current node corresponding to the `pc` is answered by `#currentNode`!
  533. !ASTPCNodeVisitor methodsFor: 'accessing'!
  534. blockIndex
  535. ^ blockIndex ifNil: [ blockIndex := 0 ]
  536. !
  537. context
  538. ^ context
  539. !
  540. context: aContext
  541. context := aContext
  542. !
  543. currentNode
  544. ^ currentNode
  545. !
  546. increaseBlockIndex
  547. blockIndex := self blockIndex + 1
  548. !
  549. pc
  550. ^ pc ifNil: [ 0 ]
  551. !
  552. pc: anInteger
  553. pc := anInteger
  554. !
  555. useInlinings
  556. ^ useInlinings ifNil: [ true ]
  557. !
  558. useInlinings: aBoolean
  559. useInlinings := aBoolean
  560. ! !
  561. !ASTPCNodeVisitor methodsFor: 'visiting'!
  562. visitBlockNode: aNode
  563. "Inlined send node. Assume that the block is inlined"
  564. (aNode parent isSendNode and: [ aNode parent shouldBeInlined ])
  565. ifFalse: [
  566. self blockIndex >= self context index ifFalse: [
  567. self increaseBlockIndex.
  568. super visitBlockNode: aNode ] ]
  569. ifTrue: [ super visitBlockNode: aNode ]
  570. !
  571. visitJSStatementNode: aNode
  572. currentNode := aNode
  573. !
  574. visitSendNode: aNode
  575. super visitSendNode: aNode.
  576. self pc = self context pc ifFalse: [
  577. aNode shouldBeInlined ifFalse: [
  578. self blockIndex = self context index ifTrue: [
  579. self pc: self pc + 1.
  580. currentNode := aNode ] ] ]
  581. ! !
  582. !Node methodsFor: '*Compiler-Interpreter'!
  583. isSteppingNode
  584. ^ false
  585. ! !
  586. !AssignmentNode methodsFor: '*Compiler-Interpreter'!
  587. isSteppingNode
  588. ^ true
  589. ! !
  590. !BlockNode methodsFor: '*Compiler-Interpreter'!
  591. isSteppingNode
  592. ^ true
  593. ! !
  594. !DynamicArrayNode methodsFor: '*Compiler-Interpreter'!
  595. isSteppingNode
  596. ^ true
  597. ! !
  598. !DynamicDictionaryNode methodsFor: '*Compiler-Interpreter'!
  599. isSteppingNode
  600. ^ true
  601. ! !
  602. !JSStatementNode methodsFor: '*Compiler-Interpreter'!
  603. isSteppingNode
  604. ^ true
  605. ! !
  606. !SendNode methodsFor: '*Compiler-Interpreter'!
  607. isSteppingNode
  608. ^ true
  609. ! !