Compiler-Semantic.st 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. isSelf
  197. ^ false
  198. !
  199. isSuper
  200. ^ false
  201. !
  202. isTempVar
  203. ^ false
  204. ! !
  205. !ScopeVar class methodsFor: 'instance creation'!
  206. on: aString
  207. ^ self new
  208. name: aString;
  209. yourself
  210. ! !
  211. ScopeVar subclass: #AliasVar
  212. slots: {}
  213. package: 'Compiler-Semantic'!
  214. !AliasVar commentStamp!
  215. I am an internally defined variable by the compiler!
  216. !AliasVar methodsFor: 'testing'!
  217. isImmutable
  218. ^ true
  219. ! !
  220. ScopeVar subclass: #ArgVar
  221. slots: {}
  222. package: 'Compiler-Semantic'!
  223. !ArgVar commentStamp!
  224. I am an argument of a method or block.!
  225. !ArgVar methodsFor: 'testing'!
  226. isImmutable
  227. ^ true
  228. ! !
  229. ScopeVar subclass: #ClassRefVar
  230. slots: {}
  231. package: 'Compiler-Semantic'!
  232. !ClassRefVar commentStamp!
  233. I am an class reference variable!
  234. !ClassRefVar methodsFor: 'accessing'!
  235. alias
  236. ^ '$globals.', self name
  237. ! !
  238. !ClassRefVar methodsFor: 'testing'!
  239. isClassRefVar
  240. ^ true
  241. !
  242. isImmutable
  243. ^ true
  244. ! !
  245. ScopeVar subclass: #ExternallyKnownVar
  246. slots: {}
  247. package: 'Compiler-Semantic'!
  248. !ExternallyKnownVar commentStamp!
  249. I am a variable known externally (not in method scope).!
  250. !ExternallyKnownVar methodsFor: 'testing'!
  251. isExternallyKnownVar
  252. ^ true
  253. ! !
  254. ScopeVar subclass: #InstanceVar
  255. slots: {}
  256. package: 'Compiler-Semantic'!
  257. !InstanceVar commentStamp!
  258. I am an instance variable of a method or block.!
  259. !InstanceVar methodsFor: 'testing'!
  260. alias
  261. ^ '$self.', self name
  262. !
  263. isInstanceVar
  264. ^ true
  265. ! !
  266. ScopeVar subclass: #PseudoVar
  267. slots: {}
  268. package: 'Compiler-Semantic'!
  269. !PseudoVar commentStamp!
  270. I am an pseudo variable.
  271. The five Smalltalk pseudo variables are: 'self', 'super', 'nil', 'true' and 'false'!
  272. !PseudoVar methodsFor: 'accessing'!
  273. alias
  274. ^ self name
  275. ! !
  276. !PseudoVar methodsFor: 'testing'!
  277. isImmutable
  278. ^ true
  279. !
  280. isPseudoVar
  281. ^ true
  282. !
  283. isSelf
  284. ^ name = 'self'
  285. ! !
  286. PseudoVar class slots: {#dictionary}!
  287. !PseudoVar class methodsFor: 'accessing'!
  288. dictionary
  289. ^ dictionary ifNil: [ dictionary := Dictionary new
  290. at: #self put: PseudoVar;
  291. at: #super put: SuperVar;
  292. at: #nil put: PseudoVar;
  293. at: #false put: PseudoVar;
  294. at: #true put: PseudoVar;
  295. at: #thisContext put: ThisContextVar;
  296. yourself ]
  297. ! !
  298. PseudoVar subclass: #SuperVar
  299. slots: {}
  300. package: 'Compiler-Semantic'!
  301. !SuperVar commentStamp!
  302. I am a 'super' pseudo variable.!
  303. !SuperVar methodsFor: 'accessing'!
  304. alias
  305. ^ '$self'
  306. !
  307. lookupAsJavaScriptSource
  308. ^ '($methodClass.superclass||$boot.nilAsClass).fn.prototype'
  309. ! !
  310. !SuperVar methodsFor: 'testing'!
  311. isSuper
  312. ^ true
  313. ! !
  314. PseudoVar subclass: #ThisContextVar
  315. slots: {}
  316. package: 'Compiler-Semantic'!
  317. !ThisContextVar commentStamp!
  318. I am a 'thisContext' pseudo variable.!
  319. !ThisContextVar methodsFor: 'accessing'!
  320. alias
  321. ^ '$core.getThisContext()'
  322. ! !
  323. ScopeVar subclass: #TempVar
  324. slots: {}
  325. package: 'Compiler-Semantic'!
  326. !TempVar commentStamp!
  327. I am an temporary variable of a method or block.!
  328. !TempVar methodsFor: 'testing'!
  329. isTempVar
  330. ^ true
  331. ! !
  332. NodeVisitor subclass: #SemanticAnalyzer
  333. slots: {#currentScope. #blockIndex. #thePackage. #theClass. #classReferences. #messageSends}
  334. package: 'Compiler-Semantic'!
  335. !SemanticAnalyzer commentStamp!
  336. I semantically analyze the abstract syntax tree and annotate it with informations such as non local returns and variable scopes.!
  337. !SemanticAnalyzer methodsFor: 'accessing'!
  338. classReferences
  339. ^ classReferences ifNil: [ classReferences := Set new ]
  340. !
  341. messageSends
  342. ^ messageSends ifNil: [ messageSends := Dictionary new ]
  343. !
  344. theClass
  345. ^ theClass
  346. !
  347. theClass: aClass
  348. theClass := aClass
  349. !
  350. thePackage
  351. ^ thePackage
  352. !
  353. thePackage: aPackage
  354. thePackage := aPackage
  355. ! !
  356. !SemanticAnalyzer methodsFor: 'error handling'!
  357. errorInvalidAssignment: aString
  358. InvalidAssignmentError new
  359. variableName: aString;
  360. signal
  361. !
  362. errorShadowingVariable: aString
  363. ShadowingVariableError new
  364. variableName: aString;
  365. signal
  366. !
  367. errorUnknownVariable: aString
  368. UnknownVariableError new
  369. variableName: aString;
  370. signal
  371. ! !
  372. !SemanticAnalyzer methodsFor: 'factory'!
  373. newBlockScope
  374. ^ self newScopeOfClass: LexicalScope
  375. !
  376. newMethodScope
  377. ^ self newScopeOfClass: MethodLexicalScope
  378. !
  379. newScopeOfClass: aLexicalScopeClass
  380. ^ aLexicalScopeClass new
  381. outerScope: currentScope;
  382. yourself
  383. ! !
  384. !SemanticAnalyzer methodsFor: 'private'!
  385. bindUnscopedVariable: aString
  386. aString isCapitalized ifTrue: [ "Capital letter variables might be globals."
  387. self classReferences add: aString.
  388. ^ ClassRefVar new name: aString; yourself ].
  389. "Throw an error if the variable is undeclared in the global JS scope (i.e. window).
  390. We allow all variables listed by Smalltalk>>#globalJsVariables.
  391. This list includes: `window`, `document`, `process` and `global`
  392. for nodejs and browser environments.
  393. This is only to make sure compilation works on both browser-based and nodejs environments.
  394. The ideal solution would be to use a pragma instead"
  395. ((Smalltalk globalJsVariables includes: aString)
  396. or: [ self isVariableKnown: aString inPackage: self thePackage ]) ifTrue: [
  397. ^ ExternallyKnownVar new name: aString; yourself ].
  398. self errorUnknownVariable: aString
  399. !
  400. nextBlockIndex
  401. blockIndex ifNil: [ blockIndex := 0 ].
  402. blockIndex := blockIndex + 1.
  403. ^ blockIndex
  404. ! !
  405. !SemanticAnalyzer methodsFor: 'scope'!
  406. popScope
  407. currentScope ifNotNil: [
  408. currentScope := currentScope outerScope ]
  409. !
  410. pushScope: aScope
  411. aScope outerScope: currentScope.
  412. currentScope := aScope
  413. !
  414. validateVariableScope: aString
  415. "Validate the variable scope in by doing a recursive lookup, up to the method scope"
  416. (currentScope lookupVariable: aString) ifNotNil: [
  417. self errorShadowingVariable: aString ]
  418. ! !
  419. !SemanticAnalyzer methodsFor: 'testing'!
  420. isVariableKnown: aString inPackage: aPackage
  421. ^ Compiler new
  422. eval: 'typeof(', aString, ')!!== "undefined"||(function(){try{return(', aString, ',true)}catch(_){return false}})()'
  423. forPackage: aPackage
  424. ! !
  425. !SemanticAnalyzer methodsFor: 'visiting'!
  426. visitAssignmentNode: aNode
  427. | lhs |
  428. super visitAssignmentNode: aNode.
  429. lhs := aNode left.
  430. lhs isImmutable ifTrue: [ self errorInvalidAssignment: lhs value ].
  431. lhs assigned: true
  432. !
  433. visitBlockNode: aNode
  434. self pushScope: self newBlockScope.
  435. aNode scope: currentScope.
  436. currentScope node: aNode.
  437. currentScope blockIndex: self nextBlockIndex.
  438. aNode parameters do: [ :each |
  439. self validateVariableScope: each.
  440. currentScope addArg: each ].
  441. super visitBlockNode: aNode.
  442. self popScope
  443. !
  444. visitCascadeNode: aNode
  445. aNode receiver: aNode dagChildren first receiver.
  446. super visitCascadeNode: aNode
  447. !
  448. visitMethodNode: aNode
  449. self pushScope: self newMethodScope.
  450. aNode scope: currentScope.
  451. currentScope node: aNode.
  452. self theClass allInstanceVariableNames do: [ :each |
  453. currentScope addIVar: each ].
  454. aNode arguments do: [ :each |
  455. self validateVariableScope: each.
  456. currentScope addArg: each ].
  457. super visitMethodNode: aNode.
  458. aNode
  459. classReferences: self classReferences;
  460. sendIndexes: self messageSends.
  461. self popScope.
  462. ^ aNode
  463. !
  464. visitReturnNode: aNode
  465. aNode scope: currentScope.
  466. currentScope isMethodScope
  467. ifTrue: [ currentScope localReturn: true ]
  468. ifFalse: [ currentScope methodScope addNonLocalReturn: currentScope ].
  469. super visitReturnNode: aNode
  470. !
  471. visitSendNode: aNode
  472. | sends |
  473. sends := self messageSends at: aNode selector ifAbsentPut: [ OrderedCollection new ].
  474. sends add: aNode.
  475. aNode index: sends size.
  476. super visitSendNode: aNode
  477. !
  478. visitSequenceNode: aNode
  479. aNode temps do: [ :each |
  480. self validateVariableScope: each.
  481. currentScope addTemp: each ].
  482. super visitSequenceNode: aNode
  483. !
  484. visitVariableNode: aNode
  485. "Bind a ScopeVar to aNode by doing a lookup in the current scope.
  486. If no var is found in scope, represent an externally known variable or throw an error."
  487. aNode binding:
  488. ((currentScope lookupVariable: aNode) ifNil: [ self bindUnscopedVariable: aNode value ])
  489. ! !
  490. !SemanticAnalyzer class methodsFor: 'instance creation'!
  491. on: aClass
  492. ^ self new
  493. theClass: aClass;
  494. yourself
  495. ! !
  496. CompilerError subclass: #SemanticError
  497. slots: {}
  498. package: 'Compiler-Semantic'!
  499. !SemanticError commentStamp!
  500. I represent an abstract semantic error thrown by the SemanticAnalyzer.
  501. Semantic errors can be unknown variable errors, etc.
  502. See my subclasses for concrete errors.
  503. The IDE should catch instances of Semantic error to deal with them when compiling!
  504. SemanticError subclass: #InvalidAssignmentError
  505. slots: {#variableName}
  506. package: 'Compiler-Semantic'!
  507. !InvalidAssignmentError commentStamp!
  508. I get signaled when a pseudo variable gets assigned.!
  509. !InvalidAssignmentError methodsFor: 'accessing'!
  510. messageText
  511. ^ ' Invalid assignment to variable: ', self variableName
  512. !
  513. variableName
  514. ^ variableName
  515. !
  516. variableName: aString
  517. variableName := aString
  518. ! !
  519. SemanticError subclass: #ShadowingVariableError
  520. slots: {#variableName}
  521. package: 'Compiler-Semantic'!
  522. !ShadowingVariableError commentStamp!
  523. I get signaled when a variable in a block or method scope shadows a variable of the same name in an outer scope.!
  524. !ShadowingVariableError methodsFor: 'accessing'!
  525. messageText
  526. ^ 'Variable shadowing error: ', self variableName, ' is already defined'
  527. !
  528. variableName
  529. ^ variableName
  530. !
  531. variableName: aString
  532. variableName := aString
  533. ! !
  534. SemanticError subclass: #UnknownVariableError
  535. slots: {#variableName}
  536. package: 'Compiler-Semantic'!
  537. !UnknownVariableError commentStamp!
  538. I get signaled when a variable is not defined.
  539. The default behavior is to allow it, as this is how Amber currently is able to seamlessly send messages to JavaScript objects.!
  540. !UnknownVariableError methodsFor: 'accessing'!
  541. messageText
  542. ^ 'Unknown Variable error: ', self variableName, ' is not defined'
  543. !
  544. variableName
  545. ^ variableName
  546. !
  547. variableName: aString
  548. variableName := aString
  549. ! !