2
0

Compiler-Interpreter.st 16 KB

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