Compiler-Semantic.st 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. Smalltalk createPackage: 'Compiler-Semantic'!
  2. Object subclass: #LexicalScope
  3. slots: {#node. #instruction. #temps. #args. #outerScope. #blockIndex}
  4. package: 'Compiler-Semantic'!
  5. !LexicalScope commentStamp!
  6. I represent a lexical scope where variable names are associated with ScopeVars
  7. Instances are used for block scopes. Method scopes are instances of MethodLexicalScope.
  8. I am attached to a ScopeVar and method/block nodes.
  9. Each context (method/closure) get a fresh scope that inherits from its outer scope.!
  10. !LexicalScope methodsFor: 'accessing'!
  11. alias
  12. ^ '$ctx', self scopeLevel asString
  13. !
  14. allVariableNames
  15. ^ self args keys, self temps keys
  16. !
  17. args
  18. ^ args ifNil: [ args := Dictionary new ]
  19. !
  20. bindingFor: aNode
  21. | identifier |
  22. identifier := aNode value.
  23. ^ self pseudoVars at: identifier ifAbsent: [
  24. self args at: identifier ifAbsent: [
  25. self temps at: identifier ifAbsent: [ nil ]]]
  26. !
  27. blockIndex
  28. ^ blockIndex ifNil: [ 0 ]
  29. !
  30. blockIndex: anInteger
  31. blockIndex := anInteger
  32. !
  33. instruction
  34. ^ instruction
  35. !
  36. instruction: anIRInstruction
  37. instruction := anIRInstruction
  38. !
  39. lookupVariable: aNode
  40. | lookup |
  41. lookup := (self bindingFor: aNode).
  42. lookup ifNil: [
  43. lookup := self outerScope ifNotNil: [
  44. (self outerScope lookupVariable: aNode) ]].
  45. ^ lookup
  46. !
  47. methodScope
  48. ^ self outerScope ifNotNil: [
  49. self outerScope methodScope ]
  50. !
  51. node
  52. "Answer the node in which I am defined"
  53. ^ node
  54. !
  55. node: aNode
  56. node := aNode
  57. !
  58. outerScope
  59. ^ outerScope
  60. !
  61. outerScope: aLexicalScope
  62. outerScope := aLexicalScope
  63. !
  64. pseudoVars
  65. ^ self methodScope pseudoVars
  66. !
  67. scopeLevel
  68. self outerScope ifNil: [ ^ 1 ].
  69. self isInlined ifTrue: [ ^ self outerScope scopeLevel ].
  70. ^ self outerScope scopeLevel + 1
  71. !
  72. temps
  73. ^ temps ifNil: [ temps := Dictionary new ]
  74. ! !
  75. !LexicalScope methodsFor: 'adding'!
  76. addArg: aString
  77. self args at: aString put: (ArgVar on: aString).
  78. (self args at: aString) scope: self
  79. !
  80. addTemp: aString
  81. self temps at: aString put: (TempVar on: aString).
  82. (self temps at: aString) scope: self
  83. ! !
  84. !LexicalScope methodsFor: 'testing'!
  85. canFlattenNonLocalReturns
  86. ^ self isInlined and: [ self outerScope canFlattenNonLocalReturns ]
  87. !
  88. isBlockScope
  89. ^ self isMethodScope not
  90. !
  91. isInlined
  92. ^ self instruction ifNil: [ false ] ifNotNil: [ :instr | instr isInlined ]
  93. !
  94. isMethodScope
  95. ^ false
  96. ! !
  97. LexicalScope subclass: #MethodLexicalScope
  98. slots: {#iVars. #pseudoVars. #localReturn. #nonLocalReturns}
  99. package: 'Compiler-Semantic'!
  100. !MethodLexicalScope commentStamp!
  101. I represent a method scope.!
  102. !MethodLexicalScope methodsFor: 'accessing'!
  103. allVariableNames
  104. ^ super allVariableNames, self iVars keys
  105. !
  106. bindingFor: aNode
  107. ^ (super bindingFor: aNode) ifNil: [
  108. self iVars at: aNode value ifAbsent: [ nil ]]
  109. !
  110. iVars
  111. ^ iVars ifNil: [ iVars := Dictionary new ]
  112. !
  113. localReturn
  114. ^ localReturn ifNil: [ false ]
  115. !
  116. localReturn: aBoolean
  117. localReturn := aBoolean
  118. !
  119. methodScope
  120. ^ self
  121. !
  122. nonLocalReturns
  123. ^ nonLocalReturns ifNil: [ nonLocalReturns := OrderedCollection new ]
  124. !
  125. pseudoVars
  126. pseudoVars ifNil: [
  127. pseudoVars := Dictionary new.
  128. PseudoVar dictionary keysAndValuesDo: [ :each :impl |
  129. pseudoVars at: each put: ((impl on: each)
  130. scope: self methodScope;
  131. yourself) ] ].
  132. ^ pseudoVars
  133. ! !
  134. !MethodLexicalScope methodsFor: 'adding'!
  135. addIVar: aString
  136. self iVars at: aString put: (InstanceVar on: aString).
  137. (self iVars at: aString) scope: self
  138. !
  139. addNonLocalReturn: aScope
  140. self nonLocalReturns add: aScope
  141. !
  142. removeNonLocalReturn: aScope
  143. self nonLocalReturns remove: aScope ifAbsent: []
  144. ! !
  145. !MethodLexicalScope methodsFor: 'testing'!
  146. canFlattenNonLocalReturns
  147. ^ true
  148. !
  149. hasLocalReturn
  150. ^ self localReturn
  151. !
  152. hasNonLocalReturn
  153. ^ self nonLocalReturns notEmpty
  154. !
  155. isMethodScope
  156. ^ true
  157. ! !
  158. Object subclass: #ScopeVar
  159. slots: {#scope. #name}
  160. package: 'Compiler-Semantic'!
  161. !ScopeVar commentStamp!
  162. I am an entry in a LexicalScope that gets associated with variable nodes of the same name.
  163. There are 4 different subclasses of vars: temp vars, local vars, args, and unknown/global vars.!
  164. !ScopeVar methodsFor: 'accessing'!
  165. alias
  166. ^ self name asVariableName
  167. !
  168. name
  169. ^ name
  170. !
  171. name: aString
  172. name := aString
  173. !
  174. scope
  175. ^ scope
  176. !
  177. scope: aScope
  178. scope := aScope
  179. ! !
  180. !ScopeVar methodsFor: 'testing'!
  181. isClassRefVar
  182. ^ false
  183. !
  184. isExternallyKnownVar
  185. ^ false
  186. !
  187. isImmutable
  188. ^ false
  189. !
  190. isInstanceVar
  191. ^ false
  192. !
  193. isPseudoVar
  194. ^ false
  195. !
  196. isSuper
  197. ^ false
  198. !
  199. isTempVar
  200. ^ false
  201. ! !
  202. !ScopeVar class methodsFor: 'instance creation'!
  203. on: aString
  204. ^ self new
  205. name: aString;
  206. yourself
  207. ! !
  208. ScopeVar subclass: #AliasVar
  209. slots: {}
  210. package: 'Compiler-Semantic'!
  211. !AliasVar commentStamp!
  212. I am an internally defined variable by the compiler!
  213. !AliasVar methodsFor: 'testing'!
  214. isImmutable
  215. ^ true
  216. ! !
  217. ScopeVar subclass: #ArgVar
  218. slots: {}
  219. package: 'Compiler-Semantic'!
  220. !ArgVar commentStamp!
  221. I am an argument of a method or block.!
  222. !ArgVar methodsFor: 'testing'!
  223. isImmutable
  224. ^ true
  225. ! !
  226. ScopeVar subclass: #ClassRefVar
  227. slots: {}
  228. package: 'Compiler-Semantic'!
  229. !ClassRefVar commentStamp!
  230. I am an class reference variable!
  231. !ClassRefVar methodsFor: 'accessing'!
  232. alias
  233. ^ '$globals.', self name
  234. ! !
  235. !ClassRefVar methodsFor: 'testing'!
  236. isClassRefVar
  237. ^ true
  238. !
  239. isImmutable
  240. ^ true
  241. ! !
  242. ScopeVar subclass: #ExternallyKnownVar
  243. slots: {}
  244. package: 'Compiler-Semantic'!
  245. !ExternallyKnownVar commentStamp!
  246. I am a variable known externally (not in method scope).!
  247. !ExternallyKnownVar methodsFor: 'testing'!
  248. isExternallyKnownVar
  249. ^ true
  250. ! !
  251. ScopeVar subclass: #InstanceVar
  252. slots: {}
  253. package: 'Compiler-Semantic'!
  254. !InstanceVar commentStamp!
  255. I am an instance variable of a method or block.!
  256. !InstanceVar methodsFor: 'testing'!
  257. alias
  258. ^ '$self.', self name
  259. !
  260. isInstanceVar
  261. ^ true
  262. ! !
  263. ScopeVar subclass: #PseudoVar
  264. slots: {}
  265. package: 'Compiler-Semantic'!
  266. !PseudoVar commentStamp!
  267. I am an pseudo variable.
  268. The five Smalltalk pseudo variables are: 'self', 'super', 'nil', 'true' and 'false'!
  269. !PseudoVar methodsFor: 'accessing'!
  270. alias
  271. ^ self name
  272. ! !
  273. !PseudoVar methodsFor: 'testing'!
  274. isImmutable
  275. ^ true
  276. !
  277. isPseudoVar
  278. ^ true
  279. ! !
  280. PseudoVar class slots: {#dictionary. #receiverNames}!
  281. !PseudoVar class methodsFor: 'accessing'!
  282. dictionary
  283. ^ dictionary ifNil: [ dictionary := Dictionary new
  284. at: #self put: PseudoVar;
  285. at: #super put: SuperVar;
  286. at: #nil put: PseudoVar;
  287. at: #false put: PseudoVar;
  288. at: #true put: PseudoVar;
  289. at: #thisContext put: ThisContextVar;
  290. yourself ]
  291. !
  292. receiverNames
  293. ^ receiverNames ifNil: [ receiverNames := Dictionary new
  294. at: #self put: '$self';
  295. at: #super put: '$self';
  296. at: #nil put: '$nil';
  297. yourself ]
  298. ! !
  299. PseudoVar subclass: #SuperVar
  300. slots: {}
  301. package: 'Compiler-Semantic'!
  302. !SuperVar commentStamp!
  303. I am a 'super' pseudo variable.!
  304. !SuperVar methodsFor: 'accessing'!
  305. lookupAsJavaScriptSource
  306. ^ '($methodClass.superclass||$boot.nilAsClass).fn.prototype'
  307. ! !
  308. !SuperVar methodsFor: 'testing'!
  309. isSuper
  310. ^ true
  311. ! !
  312. PseudoVar subclass: #ThisContextVar
  313. slots: {}
  314. package: 'Compiler-Semantic'!
  315. !ThisContextVar commentStamp!
  316. I am a 'thisContext' pseudo variable.!
  317. !ThisContextVar methodsFor: 'accessing'!
  318. alias
  319. ^ '$core.getThisContext()'
  320. ! !
  321. ScopeVar subclass: #TempVar
  322. slots: {}
  323. package: 'Compiler-Semantic'!
  324. !TempVar commentStamp!
  325. I am an temporary variable of a method or block.!
  326. !TempVar methodsFor: 'testing'!
  327. isTempVar
  328. ^ true
  329. ! !
  330. NodeVisitor subclass: #SemanticAnalyzer
  331. slots: {#currentScope. #blockIndex. #thePackage. #theClass. #classReferences. #messageSends}
  332. package: 'Compiler-Semantic'!
  333. !SemanticAnalyzer commentStamp!
  334. I semantically analyze the abstract syntax tree and annotate it with informations such as non local returns and variable scopes.!
  335. !SemanticAnalyzer methodsFor: 'accessing'!
  336. classReferences
  337. ^ classReferences ifNil: [ classReferences := Set new ]
  338. !
  339. messageSends
  340. ^ messageSends ifNil: [ messageSends := Dictionary new ]
  341. !
  342. theClass
  343. ^ theClass
  344. !
  345. theClass: aClass
  346. theClass := aClass
  347. !
  348. thePackage
  349. ^ thePackage
  350. !
  351. thePackage: aPackage
  352. thePackage := aPackage
  353. ! !
  354. !SemanticAnalyzer methodsFor: 'error handling'!
  355. errorInvalidAssignment: aString
  356. InvalidAssignmentError new
  357. variableName: aString;
  358. signal
  359. !
  360. errorShadowingVariable: aString
  361. ShadowingVariableError new
  362. variableName: aString;
  363. signal
  364. !
  365. errorUnknownVariable: aString
  366. UnknownVariableError new
  367. variableName: aString;
  368. signal
  369. ! !
  370. !SemanticAnalyzer methodsFor: 'factory'!
  371. newBlockScope
  372. ^ self newScopeOfClass: LexicalScope
  373. !
  374. newMethodScope
  375. ^ self newScopeOfClass: MethodLexicalScope
  376. !
  377. newScopeOfClass: aLexicalScopeClass
  378. ^ aLexicalScopeClass new
  379. outerScope: currentScope;
  380. yourself
  381. ! !
  382. !SemanticAnalyzer methodsFor: 'private'!
  383. bindUnscopedVariable: aString
  384. aString isCapitalized ifTrue: [ "Capital letter variables might be globals."
  385. self classReferences add: aString.
  386. ^ ClassRefVar new name: aString; yourself ].
  387. "Throw an error if the variable is undeclared in the global JS scope (i.e. window).
  388. We allow all variables listed by Smalltalk>>#globalJsVariables.
  389. This list includes: `window`, `document`, `process` and `global`
  390. for nodejs and browser environments.
  391. This is only to make sure compilation works on both browser-based and nodejs environments.
  392. The ideal solution would be to use a pragma instead"
  393. ((Smalltalk globalJsVariables includes: aString)
  394. or: [ self isVariableKnown: aString inPackage: self thePackage ]) ifTrue: [
  395. ^ ExternallyKnownVar new name: aString; yourself ].
  396. self errorUnknownVariable: aString
  397. !
  398. nextBlockIndex
  399. blockIndex ifNil: [ blockIndex := 0 ].
  400. blockIndex := blockIndex + 1.
  401. ^ blockIndex
  402. ! !
  403. !SemanticAnalyzer methodsFor: 'scope'!
  404. popScope
  405. currentScope ifNotNil: [
  406. currentScope := currentScope outerScope ]
  407. !
  408. pushScope: aScope
  409. aScope outerScope: currentScope.
  410. currentScope := aScope
  411. !
  412. validateVariableScope: aString
  413. "Validate the variable scope in by doing a recursive lookup, up to the method scope"
  414. (currentScope lookupVariable: aString) ifNotNil: [
  415. self errorShadowingVariable: aString ]
  416. ! !
  417. !SemanticAnalyzer methodsFor: 'testing'!
  418. isVariableKnown: aString inPackage: aPackage
  419. ^ Compiler new
  420. eval: 'typeof(', aString, ')!!== "undefined"||(function(){try{return(', aString, ',true)}catch(_){return false}})()'
  421. forPackage: aPackage
  422. ! !
  423. !SemanticAnalyzer methodsFor: 'visiting'!
  424. visitAssignmentNode: aNode
  425. | lhs |
  426. super visitAssignmentNode: aNode.
  427. lhs := aNode left.
  428. lhs isImmutable ifTrue: [ self errorInvalidAssignment: lhs value ].
  429. lhs assigned: true
  430. !
  431. visitBlockNode: aNode
  432. self pushScope: self newBlockScope.
  433. aNode scope: currentScope.
  434. currentScope node: aNode.
  435. currentScope blockIndex: self nextBlockIndex.
  436. aNode parameters do: [ :each |
  437. self validateVariableScope: each.
  438. currentScope addArg: each ].
  439. super visitBlockNode: aNode.
  440. self popScope
  441. !
  442. visitCascadeNode: aNode
  443. aNode receiver: aNode dagChildren first receiver.
  444. super visitCascadeNode: aNode
  445. !
  446. visitMethodNode: aNode
  447. self pushScope: self newMethodScope.
  448. aNode scope: currentScope.
  449. currentScope node: aNode.
  450. self theClass allInstanceVariableNames do: [ :each |
  451. currentScope addIVar: each ].
  452. aNode arguments do: [ :each |
  453. self validateVariableScope: each.
  454. currentScope addArg: each ].
  455. super visitMethodNode: aNode.
  456. aNode
  457. classReferences: self classReferences;
  458. sendIndexes: self messageSends.
  459. self popScope.
  460. ^ aNode
  461. !
  462. visitReturnNode: aNode
  463. aNode scope: currentScope.
  464. currentScope isMethodScope
  465. ifTrue: [ currentScope localReturn: true ]
  466. ifFalse: [ currentScope methodScope addNonLocalReturn: currentScope ].
  467. super visitReturnNode: aNode
  468. !
  469. visitSendNode: aNode
  470. | sends |
  471. sends := self messageSends at: aNode selector ifAbsentPut: [ OrderedCollection new ].
  472. sends add: aNode.
  473. aNode index: sends size.
  474. super visitSendNode: aNode
  475. !
  476. visitSequenceNode: aNode
  477. aNode temps do: [ :each |
  478. self validateVariableScope: each.
  479. currentScope addTemp: each ].
  480. super visitSequenceNode: aNode
  481. !
  482. visitVariableNode: aNode
  483. "Bind a ScopeVar to aNode by doing a lookup in the current scope.
  484. If no var is found in scope, represent an externally known variable or throw an error."
  485. aNode binding:
  486. ((currentScope lookupVariable: aNode) ifNil: [ self bindUnscopedVariable: aNode value ])
  487. ! !
  488. !SemanticAnalyzer class methodsFor: 'instance creation'!
  489. on: aClass
  490. ^ self new
  491. theClass: aClass;
  492. yourself
  493. ! !
  494. CompilerError subclass: #SemanticError
  495. slots: {}
  496. package: 'Compiler-Semantic'!
  497. !SemanticError commentStamp!
  498. I represent an abstract semantic error thrown by the SemanticAnalyzer.
  499. Semantic errors can be unknown variable errors, etc.
  500. See my subclasses for concrete errors.
  501. The IDE should catch instances of Semantic error to deal with them when compiling!
  502. SemanticError subclass: #InvalidAssignmentError
  503. slots: {#variableName}
  504. package: 'Compiler-Semantic'!
  505. !InvalidAssignmentError commentStamp!
  506. I get signaled when a pseudo variable gets assigned.!
  507. !InvalidAssignmentError methodsFor: 'accessing'!
  508. messageText
  509. ^ ' Invalid assignment to variable: ', self variableName
  510. !
  511. variableName
  512. ^ variableName
  513. !
  514. variableName: aString
  515. variableName := aString
  516. ! !
  517. SemanticError subclass: #ShadowingVariableError
  518. slots: {#variableName}
  519. package: 'Compiler-Semantic'!
  520. !ShadowingVariableError commentStamp!
  521. I get signaled when a variable in a block or method scope shadows a variable of the same name in an outer scope.!
  522. !ShadowingVariableError methodsFor: 'accessing'!
  523. messageText
  524. ^ 'Variable shadowing error: ', self variableName, ' is already defined'
  525. !
  526. variableName
  527. ^ variableName
  528. !
  529. variableName: aString
  530. variableName := aString
  531. ! !
  532. SemanticError subclass: #UnknownVariableError
  533. slots: {#variableName}
  534. package: 'Compiler-Semantic'!
  535. !UnknownVariableError commentStamp!
  536. I get signaled when a variable is not defined.
  537. The default behavior is to allow it, as this is how Amber currently is able to seamlessly send messages to JavaScript objects.!
  538. !UnknownVariableError methodsFor: 'accessing'!
  539. messageText
  540. ^ 'Unknown Variable error: ', self variableName, ' is not defined'
  541. !
  542. variableName
  543. ^ variableName
  544. !
  545. variableName: aString
  546. variableName := aString
  547. ! !