2
0

context.js 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000
  1. "use strict";
  2. var Cast = require("js/Cast.js");
  3. var Code = require("js/Code.js");
  4. var Errors = require("js/Errors.js");
  5. var Module = require("js/Module.js");
  6. var op = require("js/Operator.js");
  7. var Parser = require("parser.js");
  8. var Procedure = require("js/Procedure.js");
  9. var Class = require("rtl.js").Class;
  10. var Scope = require("js/Scope.js");
  11. var Symbol = require("js/Symbols.js");
  12. var Type = require("js/Types.js");
  13. var basicTypes = Type.basic();
  14. var nullCodeGenerator = Code.nullGenerator();
  15. var nilType = Type.nil();
  16. var castOperations = op.castOperations();
  17. function getSymbolAndScope(context, id){
  18. var s = context.findSymbol(id);
  19. if (!s)
  20. throw new Errors.Error(
  21. context instanceof Type.Module
  22. ? "identifier '" + id + "' is not exported by module '" + Type.moduleName(context) + "'"
  23. : "undeclared identifier: '" + id + "'");
  24. return s;
  25. }
  26. function getQIdSymbolAndScope(context, q){
  27. return getSymbolAndScope(q.module ? q.module : context, q.id);
  28. }
  29. function getSymbol(context, id){
  30. return getSymbolAndScope(context, id).symbol();
  31. }
  32. function unwrapTypeId(type){
  33. if (!(type instanceof Type.TypeId))
  34. throw new Errors.Error("type name expected");
  35. return type;
  36. }
  37. function unwrapType(type){
  38. return unwrapTypeId(type).type();
  39. }
  40. function getTypeSymbol(context, id){
  41. return unwrapType(getSymbol(context, id).info());
  42. }
  43. function throwTypeMismatch(from, to){
  44. throw new Errors.Error("type mismatch: expected '" + to.description() +
  45. "', got '" + from.description() + "'");
  46. }
  47. function checkTypeMatch(from, to){
  48. if (!Cast.areTypesMatch(from, to))
  49. throwTypeMismatch(from, to);
  50. }
  51. function checkImplicitCast(types, from, to){
  52. if (types.implicitCast(from, to, false, castOperations, {set: function(){}}))
  53. throwTypeMismatch(from, to);
  54. }
  55. function promoteTypeInExpression(e, type){
  56. var fromType = e.type();
  57. if (type == basicTypes.ch && fromType instanceof Type.String){
  58. var v;
  59. if (Type.stringAsChar(fromType, {set: function(value){v = value;}}))
  60. return Code.makeExpression(v, type);
  61. }
  62. return e;
  63. }
  64. function promoteExpressionType(context, left, right){
  65. var rightType = right.type();
  66. if (!left)
  67. return;
  68. var leftType = left.type();
  69. if (!rightType)
  70. return;
  71. checkImplicitCast(context.language().types, rightType, leftType);
  72. }
  73. function checkTypeCast(fromInfo, fromType, toType, msg){
  74. var prefix = "invalid " + msg;
  75. var pointerExpected = fromType instanceof Type.Pointer;
  76. if (!pointerExpected && !(fromType instanceof Type.Record))
  77. throw new Errors.Error(
  78. prefix + ": POINTER to type or RECORD expected, got '"
  79. + fromType.description() + "'");
  80. if (fromType instanceof Type.Record){
  81. if (!fromInfo.isReference())
  82. throw new Errors.Error(
  83. prefix + ": a value variable cannot be used");
  84. if (!(toType instanceof Type.Record))
  85. throw new Errors.Error(
  86. prefix + ": RECORD type expected as an argument of RECORD " + msg + ", got '"
  87. + toType.description() + "'");
  88. }
  89. else if (fromType instanceof Type.Pointer)
  90. if (!(toType instanceof Type.Pointer))
  91. throw new Errors.Error(
  92. prefix + ": POINTER type expected as an argument of POINTER " + msg + ", got '"
  93. + toType.description() + "'");
  94. if (fromType instanceof Type.Pointer)
  95. fromType = Type.pointerBase(fromType);
  96. if (toType instanceof Type.Pointer)
  97. toType = Type.pointerBase(toType);
  98. var t = Type.recordBase(toType);
  99. while (t && t != fromType)
  100. t = Type.recordBase(t);
  101. if (!t)
  102. throw new Errors.Error(prefix + ": '" + toType.description()
  103. + "' is not an extension of '" + fromType.description() + "'");
  104. }
  105. var ChainedContext = Class.extend({
  106. init: function ChainedContext(parent){this.__parent = parent;},
  107. parent: function(){return this.__parent;},
  108. handleMessage: function(msg){return this.__parent.handleMessage(msg);},
  109. language: function(){return this.__parent.language();},
  110. codeGenerator: function(){return this.__parent.codeGenerator();},
  111. findSymbol: function(id){return this.__parent.findSymbol(id);},
  112. currentScope: function(s){return this.__parent.currentScope();},
  113. pushScope: function(scope){this.__parent.pushScope(scope);},
  114. popScope: function(){this.__parent.popScope();},
  115. setType: function(type){this.__parent.setType(type);},
  116. setDesignator: function(d){this.__parent.setDesignator(d);},
  117. handleExpression: function(e){this.__parent.handleExpression(e);},
  118. handleLiteral: function(s){this.__parent.handleLiteral(s);},
  119. handleConst: function(type, value, code){this.__parent.handleConst(type, value, code);},
  120. genTypeName: function(){return this.__parent.genTypeName();},
  121. genVarName: function(id){return this.__parent.genVarName(id);},
  122. qualifyScope: function(scope){return this.__parent.qualifyScope(scope);}
  123. });
  124. exports.Integer = ChainedContext.extend({
  125. init: function IntegerContext(context){
  126. ChainedContext.prototype.init.call(this, context);
  127. this.__result = "";
  128. this.__isHex = false;
  129. },
  130. isLexem: function(){return true;},
  131. handleChar: function(c){this.__result += String.fromCharCode(c);},
  132. handleLiteral: function(){this.__isHex = true;},
  133. toInt: function(s){return parseInt(this.__result, 10);},
  134. endParse: function(){
  135. var n = this.toInt();
  136. this.parent().handleConst(basicTypes.integer, Code.makeIntConst(n), n.toString());
  137. }
  138. });
  139. exports.HexInteger = exports.Integer.extend({
  140. init: function HexIntegerContext(context){
  141. exports.Integer.prototype.init.call(this, context);
  142. },
  143. toInt: function(s){return parseInt(this.__result, 16);}
  144. });
  145. exports.Real = ChainedContext.extend({
  146. init: function RealContext(context){
  147. ChainedContext.prototype.init.call(this, context);
  148. this.__result = "";
  149. },
  150. isLexem: function(){return true;},
  151. handleChar: function(c){this.__result += String.fromCharCode(c);},
  152. handleLiteral: function(s){
  153. if (s == "D") // LONGREAL
  154. s = "E";
  155. this.__result += s;
  156. },
  157. endParse: function(){
  158. var n = Number(this.__result);
  159. this.parent().handleConst(basicTypes.real, Code.makeRealConst(n), n.toString());
  160. }
  161. });
  162. function escapeString(s){
  163. var escapeChars = {"\\": "\\\\",
  164. "\"": "\\\"",
  165. "\n": "\\n",
  166. "\r": "\\r",
  167. "\t": "\\t",
  168. "\b": "\\b",
  169. "\f": "\\f"
  170. };
  171. var result = "\"";
  172. for(var i = 0; i < s.length; ++i){
  173. var c = s[i];
  174. var escape = escapeChars[c];
  175. result += escape !== undefined ? escape : c;
  176. }
  177. return result + "\"";
  178. }
  179. exports.String = ChainedContext.extend({
  180. init: function StringContext(context){
  181. ChainedContext.prototype.init.call(this, context);
  182. this.__result = undefined;
  183. },
  184. handleString: function(s){this.__result = s;},
  185. toStr: function(s){return s;},
  186. endParse: function(){
  187. var s = this.toStr(this.__result);
  188. this.parent().handleConst(Type.makeString(s), Code.makeStringConst(s), escapeString(s));
  189. }
  190. });
  191. exports.Char = exports.String.extend({
  192. init: function CharContext(context){
  193. exports.String.prototype.init.call(this, context);
  194. this.__result = "";
  195. },
  196. handleChar: function(c){this.__result += String.fromCharCode(c);},
  197. toStr: function(s){return String.fromCharCode(parseInt(s, 16));}
  198. });
  199. exports.BaseType = ChainedContext.extend({
  200. init: function BaseTypeContext(context){
  201. ChainedContext.prototype.init.call(this, context);
  202. },
  203. handleQIdent: function(q){
  204. var s = getQIdSymbolAndScope(this, q);
  205. this.parent().setBaseType(unwrapType(s.symbol().info()));
  206. }
  207. });
  208. exports.QualifiedIdentificator = ChainedContext.extend({
  209. init: function QualifiedIdentificator(context){
  210. ChainedContext.prototype.init.call(this, context);
  211. this.__module = undefined;
  212. this.__id = undefined;
  213. this.__code = "";
  214. },
  215. handleIdent: function(id){
  216. this.__id = id;
  217. },
  218. handleLiteral: function(){
  219. var s = getSymbol(this, this.__id);
  220. if (!s.isModule())
  221. return false; // stop parsing
  222. this.__module = s.info();
  223. this.__code = this.__id + ".";
  224. return undefined;
  225. },
  226. endParse: function(){
  227. var code = this.__code + this.__id;
  228. this.parent().handleQIdent({
  229. module: this.__module,
  230. id: this.__id,
  231. code: code
  232. });
  233. }
  234. });
  235. var IdentdefInfo = Class.extend({
  236. init: function Context$Identdef(id, exported){
  237. this.__id = id;
  238. this.__exported = exported;
  239. },
  240. id: function(){return this.__id;},
  241. exported: function(){return this.__exported;}
  242. });
  243. exports.Identdef = ChainedContext.extend({
  244. init: function IdentdefContext(context){
  245. ChainedContext.prototype.init.call(this, context);
  246. this._id = undefined;
  247. this._export = false;
  248. },
  249. handleIdent: function(id){this._id = id;},
  250. handleLiteral: function(){this._export = true;},
  251. endParse: function(){
  252. this.parent().handleIdentdef(this._makeIdendef());
  253. },
  254. _makeIdendef: function(){
  255. return new IdentdefInfo(this._id, this._export);
  256. }
  257. });
  258. function castCode(type, context){
  259. var baseType = type instanceof Type.Pointer ? Type.pointerBase(type) : type;
  260. return context.qualifyScope(Type.recordScope(baseType)) + Type.recordConstructor(baseType);
  261. }
  262. exports.Designator = ChainedContext.extend({
  263. init: function Context$Designator(context){
  264. ChainedContext.prototype.init.call(this, context);
  265. this.__currentType = undefined;
  266. this.__info = undefined;
  267. this.__scope = undefined;
  268. this.__code = "";
  269. this.__lval = undefined;
  270. this.__indexExpression = undefined;
  271. this.__derefCode = undefined;
  272. this.__propCode = undefined;
  273. },
  274. handleQIdent: function(q){
  275. var found = getQIdSymbolAndScope(this, q);
  276. this.__scope = found.scope();
  277. var s = found.symbol();
  278. var info = s.info();
  279. if (info instanceof Type.Type || s.isType())
  280. this.__currentType = info;
  281. else if (s.isConst())
  282. this.__currentType = Type.constType(info);
  283. else if (s.isVariable())
  284. this.__currentType = info.type();
  285. else if (s.isProcedure())
  286. this.__currentType = Type.procedureType(info);
  287. this.__info = info;
  288. this.__code += q.code;
  289. if (q.module && s.isVariable())
  290. this.__code += "()";
  291. },
  292. handleIdent: function(id){
  293. var t = this.__currentType;
  294. var pointerType;
  295. var isReadOnly = this.__info instanceof Type.Variable
  296. && this.__info.isReadOnly();
  297. if (t instanceof Type.Pointer){
  298. pointerType = t;
  299. this.__handleDeref();
  300. isReadOnly = false;
  301. }
  302. else if (!(t instanceof Type.Record
  303. || t instanceof Module.AnyType))
  304. throw new Errors.Error("cannot designate '" + t.description() + "'");
  305. var field = this.__denote(id, pointerType);
  306. this.__info = this._makeDenoteVar(field, isReadOnly);
  307. this.__currentType = field.type();
  308. this.__scope = undefined;
  309. },
  310. _makeDenoteVar: function(field, isReadOnly){
  311. return Type.makeVariable(field.type(), isReadOnly);
  312. },
  313. handleExpression: function(e){this.__indexExpression = e;},
  314. __handleIndexExpression: function(){
  315. var e = this.__indexExpression;
  316. var expType = e.type();
  317. if (!Type.isInt(expType))
  318. throw new Errors.Error(
  319. Type.intsDescription() + " expression expected, got '" + expType.description() + "'");
  320. var index = this._indexSequence(this.__currentType, this.__info);
  321. var length = index.length;
  322. var pValue = e.constValue();
  323. if (pValue){
  324. var value = pValue.value;
  325. if (value < 0)
  326. throw new Errors.Error("index is negative: " + value);
  327. if (length != Type.openArrayLength && value >= length)
  328. throw new Errors.Error("index out of bounds: maximum possible index is "
  329. + (length - 1)
  330. + ", got " + value );
  331. }
  332. return index;
  333. },
  334. _advance: function(type, info, code){
  335. this.__currentType = type;
  336. this.__info = info;
  337. this.__code = code;
  338. },
  339. _indexSequence: function(type, info){
  340. var isArray = type instanceof Type.Array;
  341. if (!isArray && !(type instanceof Type.String))
  342. throw new Errors.Error("ARRAY or string expected, got '" + type.description() + "'");
  343. var length = isArray ? Type.arrayLength(type) : Type.stringLen(type);
  344. if (!isArray && !length)
  345. throw new Errors.Error("cannot index empty string" );
  346. var indexType = isArray ? Type.arrayElementsType(type) : basicTypes.ch;
  347. return { length: length,
  348. type: indexType,
  349. info: Type.makeVariable(indexType, info instanceof Type.Const || info.isReadOnly())
  350. };
  351. },
  352. handleLiteral: function(s){
  353. if (s == "]" || s == ","){
  354. var index = this.__handleIndexExpression();
  355. var indexCode = Code.derefExpression(this.__indexExpression).code();
  356. this.__propCode = indexCode;
  357. var code = this.__derefCode + "[" + indexCode + "]";
  358. if (index.type == basicTypes.ch){
  359. this.__lval = code;
  360. code = this.__derefCode + ".charCodeAt(" + indexCode + ")";
  361. }
  362. this._advance(index.type, index.info, this.__code + code);
  363. }
  364. if (s == "[" || s == ","){
  365. this.__derefCode = this.__code;
  366. this.__code = "";
  367. }
  368. else if (s == "^"){
  369. this.__handleDeref();
  370. this.__info = Type.makeVariableRef(this.__currentType, false);
  371. }
  372. },
  373. __handleDeref: function(){
  374. if (!(this.__currentType instanceof Type.Pointer))
  375. throw new Errors.Error("POINTER TO type expected, got '"
  376. + this.__currentType.description() + "'");
  377. this.__currentType = Type.pointerBase(this.__currentType);
  378. if (this.__currentType instanceof Type.NonExportedRecord)
  379. throw new Errors.Error("POINTER TO non-exported RECORD type cannot be dereferenced");
  380. },
  381. handleTypeCast: function(type){
  382. checkTypeCast(this.__info, this.__currentType, type, "type cast");
  383. var code = this.language().rtl.typeGuard(this.__code, castCode(type, this));
  384. this.__code = code;
  385. this.__currentType = type;
  386. },
  387. __denote: function(id, pointerType){
  388. var t = this.__currentType;
  389. var field = t.findSymbol(id);
  390. if (!field){
  391. var typeDesc = !Type.typeName(t) && pointerType && Type.typeName(pointerType)
  392. ? Type.typeName(pointerType)
  393. : t.description();
  394. throw new Errors.Error("type '" + typeDesc + "' has no '" + id + "' field");
  395. }
  396. this.__derefCode = this.__code;
  397. this.__propCode = "\"" + id + "\"";
  398. this.__code += "." + id;
  399. return field;
  400. },
  401. endParse: function(){
  402. var code = this.__code;
  403. var self = this;
  404. var refCode = function(code){return self.__makeRefCode(code);};
  405. this.parent().setDesignator(
  406. Code.makeDesignator(code, this.__lval ? this.__lval : code, refCode, this.__currentType, this.__info, this.__scope));
  407. },
  408. __makeRefCode: function(code){
  409. if ( this.__currentType instanceof Type.Array
  410. || this.__currentType instanceof Type.Record
  411. || this.__info.isReference())
  412. return code;
  413. if (this.__derefCode)
  414. return this.language().rtl.makeRef(this.__derefCode, this.__propCode);
  415. return "{set: function($v){" + code + " = $v;}, get: function(){return " + code + ";}}";
  416. }
  417. });
  418. exports.Type = ChainedContext.extend({
  419. init: function Context$Type(context){
  420. ChainedContext.prototype.init.call(this, context);
  421. },
  422. handleQIdent: function(q){
  423. this.parent().handleQIdent(q);
  424. }
  425. });
  426. var HandleSymbolAsType = ChainedContext.extend({
  427. init: function Context$HandleSymbolAsType(context){
  428. ChainedContext.prototype.init.call(this, context);
  429. },
  430. handleQIdent: function(q){
  431. var s = getQIdSymbolAndScope(this, q);
  432. this.setType(unwrapType(s.symbol().info()));
  433. }
  434. });
  435. exports.FormalType = HandleSymbolAsType.extend({
  436. init: function FormalType(context){
  437. HandleSymbolAsType.prototype.init.call(this, context);
  438. this.__arrayDimension = 0;
  439. },
  440. setType: function(type){
  441. for(var i = 0; i < this.__arrayDimension; ++i)
  442. type = Type.makeArray("ARRAY OF " + Type.typeName(type),
  443. undefined,
  444. type,
  445. 0);
  446. this.parent().setType(type);
  447. },
  448. handleLiteral: function(s){
  449. if (s == "ARRAY")
  450. ++this.__arrayDimension;
  451. }
  452. });
  453. var ProcArg = Class.extend({
  454. init: function(type, isVar){
  455. this.type = type;
  456. this.isVar = isVar;
  457. },
  458. description: function(){
  459. return (this.isVar ? "VAR " : "") + this.type.description();
  460. }
  461. });
  462. function AddArgumentMsg(name, arg){
  463. this.name = name;
  464. this.arg = arg;
  465. }
  466. exports.FormalParameters = ChainedContext.extend({
  467. init: function FormalParametersContext(context){
  468. ChainedContext.prototype.init.call(this, context);
  469. this.__arguments = [];
  470. this.__result = undefined;
  471. var parent = this.parent();
  472. var name = parent.typeName();
  473. if (name === undefined)
  474. name = "";
  475. this.__type = new Procedure.make(name);
  476. parent.setType(this.__type);
  477. },
  478. handleMessage: function(msg){
  479. if (msg instanceof AddArgumentMsg){
  480. this.__arguments.push(msg.arg);
  481. return undefined;
  482. }
  483. return ChainedContext.prototype.handleMessage.call(this, msg);
  484. },
  485. handleQIdent: function(q){
  486. var s = getQIdSymbolAndScope(this, q);
  487. var resultType = unwrapType(s.symbol().info());
  488. if (resultType instanceof Type.Array)
  489. throw new Errors.Error("the result type of a procedure cannot be an ARRAY");
  490. if (resultType instanceof Type.Record)
  491. throw new Errors.Error("the result type of a procedure cannot be a RECORD");
  492. this.__result = resultType;
  493. },
  494. endParse: function(){
  495. this.__type.define(this.__arguments, this.__result);
  496. }
  497. });
  498. function endParametersMsg(){}
  499. exports.FormalParametersProcDecl = exports.FormalParameters.extend({
  500. init: function FormalParametersProcDeclContext(context){
  501. exports.FormalParameters.prototype.init.call(this, context);
  502. },
  503. handleMessage: function(msg){
  504. var result = exports.FormalParameters.prototype.handleMessage.call(this, msg);
  505. if (msg instanceof AddArgumentMsg)
  506. this.parent().handleMessage(msg);
  507. return result;
  508. },
  509. endParse: function(){
  510. exports.FormalParameters.prototype.endParse.call(this);
  511. this.handleMessage(endParametersMsg);
  512. }
  513. });
  514. exports.ProcDecl = ChainedContext.extend({
  515. init: function ProcDeclContext(context){
  516. ChainedContext.prototype.init.call(this, context);
  517. this.__id = undefined;
  518. this.__firstArgument = true;
  519. this.__type = undefined;
  520. this.__returnParsed = false;
  521. this.__outerScope = this.parent().currentScope();
  522. this.__stdSymbols = this.language().stdSymbols;
  523. },
  524. handleIdentdef: function(id){
  525. this.__id = id;
  526. this.codeGenerator().write(this._prolog());
  527. this.parent().pushScope(Scope.makeProcedure(this.__stdSymbols));
  528. },
  529. handleIdent: function(id){
  530. if (this.__id.id() != id)
  531. throw new Errors.Error("mismatched procedure names: '" + this.__id.id()
  532. + "' at the begining and '" + id + "' at the end");
  533. this.codeGenerator().closeScope("");
  534. this.parent().popScope();
  535. },
  536. _prolog: function(){return "\nfunction " + this.__id.id() + "(";},
  537. typeName: function(){return undefined;},
  538. setType: function(type){
  539. var procSymbol = Symbol.makeSymbol(
  540. this.__id.id(),
  541. Type.makeProcedure(type));
  542. this.__outerScope.addSymbol(procSymbol, this.__id.exported());
  543. this.__type = type;
  544. },
  545. __addArgument: function(name, arg){
  546. if (name == this.__id.id())
  547. throw new Errors.Error("argument '" + name + "' has the same name as procedure");
  548. var v = this._makeArgumentVariable(arg);
  549. var s = Symbol.makeSymbol(name, v);
  550. this.currentScope().addSymbol(s);
  551. var code = this.codeGenerator();
  552. if (!this.__firstArgument)
  553. code.write(", ");
  554. else
  555. this.__firstArgument = false;
  556. code.write(name + "/*" + arg.description() + "*/");
  557. },
  558. _makeArgumentVariable: function(arg){
  559. var readOnly = !arg.isVar
  560. && (arg.type instanceof Type.Array || arg.type instanceof Type.Record);
  561. return arg.isVar ? Type.makeVariableRef(arg.type)
  562. : Type.makeVariable(arg.type, readOnly);
  563. },
  564. handleMessage: function(msg){
  565. if (msg == endParametersMsg){
  566. var code = this.codeGenerator();
  567. code.write(")");
  568. code.openScope();
  569. return undefined;
  570. }
  571. if (msg instanceof AddArgumentMsg)
  572. return this.__addArgument(msg.name, msg.arg);
  573. return ChainedContext.prototype.handleMessage.call(this, msg);
  574. },
  575. handleReturn: function(type){
  576. var result = this.__type.result();
  577. if (!result)
  578. throw new Errors.Error("unexpected RETURN in PROCEDURE declared with no result type");
  579. if (this.language().types.implicitCast(type, result, false, castOperations, {set: function(){}}))
  580. throw new Errors.Error(
  581. "RETURN '" + result.description() + "' expected, got '"
  582. + type.description() + "'");
  583. this.__returnParsed = true;
  584. },
  585. endParse: function(){
  586. var result = this.__type.result();
  587. if (result && !this.__returnParsed)
  588. throw new Errors.Error("RETURN expected at the end of PROCEDURE declared with '"
  589. + Type.typeName(result) + "' result type");
  590. }
  591. });
  592. exports.Return = ChainedContext.extend({
  593. init: function Context$Return(context){
  594. ChainedContext.prototype.init.call(this, context);
  595. this.__expr = undefined;
  596. },
  597. codeGenerator: function(){return nullCodeGenerator;},
  598. handleExpression: function(e){this.__expr = e;},
  599. endParse: function(){
  600. var parent = this.parent();
  601. parent.codeGenerator().write("return " + Code.derefExpression(this.__expr).code() + ";\n");
  602. parent.handleReturn(this.__expr.type());
  603. }
  604. });
  605. exports.ProcParams = HandleSymbolAsType.extend({
  606. init: function Context$ProcParams(context){
  607. HandleSymbolAsType.prototype.init.call(this, context);
  608. this.__isVar = false;
  609. this.__argNamesForType = [];
  610. },
  611. handleLiteral: function(s){
  612. if (s == "VAR")
  613. this.__isVar = true;
  614. },
  615. handleIdent: function(id){ this.__argNamesForType.push(id);},
  616. setType: function(type){
  617. var names = this.__argNamesForType;
  618. for(var i = 0; i < names.length; ++i){
  619. var name = names[i];
  620. this.handleMessage(
  621. new AddArgumentMsg(name, Type.makeProcedureArgument(type, this.__isVar)));
  622. }
  623. this.__isVar = false;
  624. this.__argNamesForType = [];
  625. }
  626. });
  627. exports.PointerDecl = ChainedContext.extend({
  628. init: function Context$PointerDecl(context){
  629. ChainedContext.prototype.init.call(this, context);
  630. },
  631. handleQIdent: function(q){
  632. var id = q.id;
  633. var s = q.module
  634. ? getQIdSymbolAndScope(this, q)
  635. : this.findSymbol(id);
  636. var info;
  637. if (s)
  638. info = s.symbol().info();
  639. else {
  640. var scope = this.currentScope();
  641. Scope.addUnresolved(scope, id);
  642. var resolve = function(){return getSymbol(this, id).info().type();}.bind(this);
  643. info = Type.makeForwardTypeId(resolve);
  644. }
  645. var typeId = unwrapTypeId(info);
  646. this.__setTypeId(typeId);
  647. },
  648. __setTypeId: function(typeId){
  649. if (!(typeId instanceof Type.ForwardTypeId)){
  650. var type = typeId.type();
  651. if (!(type instanceof Type.Record))
  652. throw new Errors.Error(
  653. "RECORD is expected as a POINTER base type, got '" + type.description() + "'");
  654. }
  655. var parent = this.parent();
  656. var name = parent.isAnonymousDeclaration()
  657. ? ""
  658. : parent.genTypeName();
  659. var pointerType = Type.makePointer(name, typeId);
  660. parent.setType(pointerType);
  661. },
  662. setType: function(type){
  663. var typeId = Type.makeTypeId(type);
  664. this.currentScope().addFinalizer(function(){typeId.strip();});
  665. this.__setTypeId(typeId);
  666. },
  667. isAnonymousDeclaration: function(){return true;},
  668. exportField: function(field){
  669. throw new Errors.Error( "cannot export anonymous RECORD field: '" + field + "'");
  670. }
  671. });
  672. exports.ArrayDecl = HandleSymbolAsType.extend({
  673. init: function Context$ArrayDecl(context){
  674. HandleSymbolAsType.prototype.init.call(this, context);
  675. this.__dimensions = undefined;
  676. },
  677. handleDimensions: function(dimensions){this.__dimensions = dimensions;},
  678. setType: function(type){
  679. var initializer = type instanceof Type.Array || type instanceof Type.Record
  680. ? "function(){return " + type.initializer(this) + ";}"
  681. : type.initializer(this);
  682. var isCharArray = (type == basicTypes.ch);
  683. var dimensions = "";
  684. for(var i = this.__dimensions.length; i-- ;){
  685. var length = this.__dimensions[i];
  686. dimensions = length + (dimensions.length ? ", " + dimensions : "");
  687. var rtl = this.language().rtl;
  688. var arrayInit = !i
  689. ? isCharArray ? rtl.makeCharArray(dimensions)
  690. : rtl.makeArray(dimensions + ", " + initializer)
  691. : undefined;
  692. type = Type.makeArray("ARRAY OF " + Type.typeName(type),
  693. arrayInit,
  694. type,
  695. length);
  696. }
  697. this.__type = type;
  698. },
  699. isAnonymousDeclaration: function(){return true;},
  700. endParse: function(){this.parent().setType(this.__type);}
  701. });
  702. exports.ArrayDimensions = ChainedContext.extend({
  703. init: function ArrayDimensionsContext(context){
  704. ChainedContext.prototype.init.call(this, context);
  705. this.__dimensions = [];
  706. },
  707. codeGenerator: function(){return nullCodeGenerator;},
  708. handleExpression: function(e){
  709. var type = e.type();
  710. if (type !== basicTypes.integer)
  711. throw new Errors.Error("'INTEGER' constant expression expected, got '" + type.description() + "'");
  712. var value = e.constValue();
  713. if (!value)
  714. throw new Errors.Error("constant expression expected as ARRAY size");
  715. if (value.value <= 0)
  716. throw new Errors.Error("array size must be greater than 0, got " + value.value);
  717. this.__dimensions.push(value.value);
  718. },
  719. endParse: function(){
  720. this.parent().handleDimensions(this.__dimensions);
  721. }
  722. });
  723. var numericOpTypeCheck = {
  724. expect: "numeric type",
  725. check: function(t){return Type.numeric().indexOf(t) != -1;}
  726. };
  727. var numericOrSetOpTypeCheck = {
  728. expect: numericOpTypeCheck.expect + " or SET",
  729. check: function(t){return numericOpTypeCheck.check(t) || t == basicTypes.set;}
  730. };
  731. var intOpTypeCheck = {
  732. expect: Type.intsDescription(),
  733. check: Type.isInt
  734. };
  735. function throwOperatorTypeMismatch(op, expect, type){
  736. throw new Errors.Error(
  737. "operator '" + op +
  738. "' type mismatch: " + expect + " expected, got '" +
  739. type.description() + "'");
  740. }
  741. function assertOpType(type, check, literal){
  742. if (!check.check(type))
  743. throwOperatorTypeMismatch(literal, check.expect, type);
  744. }
  745. function assertNumericOp(type, literal, op, intOp){
  746. assertOpType(type, numericOpTypeCheck, literal);
  747. return (intOp && Type.isInt(type))
  748. ? intOp : op;
  749. }
  750. function assertNumericOrSetOp(type, literal, op, intOp, setOp){
  751. assertOpType(type, numericOrSetOpTypeCheck, literal);
  752. return Type.isInt(type) ? intOp : type == basicTypes.set ? setOp : op;
  753. }
  754. function assertIntOp(type, literal, op){
  755. assertOpType(type, intOpTypeCheck, literal);
  756. return op;
  757. }
  758. function useIntOrderOp(t){
  759. return Type.isInt(t) || t == basicTypes.ch;
  760. }
  761. function useIntEqOp(t){
  762. return Type.isInt(t)
  763. || t == basicTypes.bool
  764. || t == basicTypes.ch
  765. || t instanceof Type.Pointer
  766. || t instanceof Type.Procedure
  767. || t == nilType;
  768. }
  769. var RelationOps = Class.extend({
  770. init: function RelationOps(){
  771. },
  772. eq: function(type){
  773. return useIntEqOp(type) ? op.equalInt
  774. : Type.isString(type) ? op.equalStr
  775. : type == basicTypes.real ? op.equalReal
  776. : type == basicTypes.set ? op.equalSet
  777. : undefined;
  778. },
  779. notEq: function(type){
  780. return useIntEqOp(type) ? op.notEqualInt
  781. : Type.isString(type) ? op.notEqualStr
  782. : type == basicTypes.real ? op.notEqualReal
  783. : type == basicTypes.set ? op.notEqualSet
  784. : undefined;
  785. },
  786. less: function(type){
  787. return useIntOrderOp(type) ? op.lessInt
  788. : Type.isString(type) ? op.lessStr
  789. : type == basicTypes.real ? op.lessReal
  790. : undefined;
  791. },
  792. greater: function(type){
  793. return useIntOrderOp(type) ? op.greaterInt
  794. : Type.isString(type) ? op.greaterStr
  795. : type == basicTypes.real ? op.greaterReal
  796. : undefined;
  797. },
  798. lessEq: function(type){
  799. return useIntOrderOp(type) ? op.eqLessInt
  800. : Type.isString(type) ? op.eqLessStr
  801. : type == basicTypes.real ? op.eqLessReal
  802. : type == basicTypes.set ? op.setInclL
  803. : undefined;
  804. },
  805. greaterEq: function(type){
  806. return useIntOrderOp(type) ? op.eqGreaterInt
  807. : Type.isString(type) ? op.eqGreaterStr
  808. : type == basicTypes.real ? op.eqGreaterReal
  809. : type == basicTypes.set ? op.setInclR
  810. : undefined;
  811. },
  812. is: function(type, context){
  813. return function(left, right){
  814. var d = left.designator();
  815. checkTypeCast(d ? d.info() : undefined, left.type(), type, "type test");
  816. return op.is(left, Code.makeExpression(castCode(type, context)));
  817. };
  818. },
  819. eqExpect: function(){return "numeric type or SET or BOOLEAN or CHAR or character array or POINTER or PROCEDURE";},
  820. strongRelExpect: function(){return "numeric type or CHAR or character array";},
  821. relExpect: function(){return "numeric type or SET or CHAR or character array";},
  822. coalesceType: function(leftType, rightType){
  823. if (leftType instanceof Type.Pointer && rightType instanceof Type.Pointer){
  824. var type = Cast.findPointerBaseType(leftType, rightType);
  825. if (!type)
  826. type = Cast.findPointerBaseType(rightType, leftType);
  827. if (type)
  828. return type;
  829. }
  830. // special case for strings
  831. var isStrings = Type.isString(leftType) && Type.isString(rightType);
  832. if (!isStrings)
  833. checkTypeMatch(rightType, leftType);
  834. return leftType;
  835. }
  836. });
  837. var relationOps = new RelationOps();
  838. function checkSetHasBit(leftType, rightType, context){
  839. if (!Type.isInt(leftType))
  840. throw new Errors.Error(
  841. Type.intsDescription() + " expected as an element of SET, got '" + Type.typeName(leftType) + "'");
  842. checkImplicitCast(context.language().types, rightType, basicTypes.set);
  843. }
  844. function relationOp(leftType, rightType, literal, ops, context){
  845. var type =
  846. literal == "IS" ? unwrapType(rightType)
  847. : literal == "IN" ? checkSetHasBit(leftType, rightType, context)
  848. : ops.coalesceType(leftType, rightType);
  849. var o;
  850. var mismatch;
  851. switch (literal){
  852. case "=":
  853. o = ops.eq(type);
  854. if (!o)
  855. mismatch = ops.eqExpect();
  856. break;
  857. case "#":
  858. o = ops.notEq(type);
  859. if (!o)
  860. mismatch = ops.eqExpect();
  861. break;
  862. case "<":
  863. o = ops.less(type);
  864. if (!o)
  865. mismatch = ops.strongRelExpect();
  866. break;
  867. case ">":
  868. o = ops.greater(type);
  869. if (!o)
  870. mismatch = ops.strongRelExpect();
  871. break;
  872. case "<=":
  873. o = ops.lessEq(type);
  874. if (!o)
  875. mismatch = ops.relExpect();
  876. break;
  877. case ">=":
  878. o = ops.greaterEq(type);
  879. if (!o)
  880. mismatch = ops.relExpect();
  881. break;
  882. case "IS":
  883. o = ops.is(type, context);
  884. break;
  885. case "IN":
  886. o = op.setHasBit;
  887. break;
  888. }
  889. if (mismatch)
  890. throwOperatorTypeMismatch(literal, mismatch, type);
  891. return o;
  892. }
  893. exports.AddOperator = ChainedContext.extend({
  894. init: function AddOperatorContext(context){
  895. ChainedContext.prototype.init.call(this, context);
  896. },
  897. handleLiteral: function(s){
  898. var parent = this.parent();
  899. var type = parent.type();
  900. var o = this.__matchOperator(s, type);
  901. if (o)
  902. parent.handleBinaryOperator(o);
  903. },
  904. __matchOperator: function(s, type){
  905. var result;
  906. switch (s){
  907. case "+":
  908. result = this._matchPlusOperator(type);
  909. if (!result)
  910. throwOperatorTypeMismatch(s, this._expectPlusOperator(), type);
  911. break;
  912. case "-":
  913. return assertNumericOrSetOp(type, s, op.subReal, op.subInt, op.setDiff);
  914. case "OR":
  915. if (type != basicTypes.bool)
  916. throw new Errors.Error("BOOLEAN expected as operand of 'OR', got '"
  917. + type.description() + "'");
  918. return op.or;
  919. }
  920. return result;
  921. },
  922. _matchPlusOperator: function(type){
  923. if (type == basicTypes.set)
  924. return op.setUnion;
  925. if (Type.isInt(type))
  926. return op.addInt;
  927. if (type == basicTypes.real)
  928. return op.addReal;
  929. return undefined;
  930. },
  931. _expectPlusOperator: function(){return "numeric type or SET";}
  932. });
  933. exports.MulOperator = ChainedContext.extend({
  934. init: function MulOperatorContext(context){
  935. ChainedContext.prototype.init.call(this, context);
  936. },
  937. handleLiteral: function(s){
  938. var parent = this.parent();
  939. var type = parent.type();
  940. var o;
  941. if (s == "*")
  942. o = assertNumericOrSetOp(type, s, op.mulReal, op.mulInt, op.setIntersection);
  943. else if (s == "/"){
  944. if (Type.isInt(type))
  945. throw new Errors.Error("operator DIV expected for integer division");
  946. o = assertNumericOrSetOp(type, s, op.divReal, undefined, op.setSymmetricDiff);
  947. }
  948. else if (s == "DIV")
  949. o = assertIntOp(type, s, op.divInt);
  950. else if (s == "MOD")
  951. o = assertIntOp(type, s, op.mod);
  952. else if (s == "&"){
  953. if (type != basicTypes.bool)
  954. throw new Errors.Error("BOOLEAN expected as operand of '&', got '"
  955. + type.description() + "'");
  956. o = op.and;
  957. }
  958. if (o)
  959. parent.handleOperator(o);
  960. }
  961. });
  962. exports.Term = ChainedContext.extend({
  963. init: function TermContext(context){
  964. ChainedContext.prototype.init.call(this, context);
  965. this.__logicalNot = false;
  966. this.__operator = undefined;
  967. this.__expression = undefined;
  968. },
  969. type: function(){return this.__expression.type();},
  970. setDesignator: function(d){
  971. var info = d.info();
  972. if (info instanceof Type.ProcedureId){
  973. var proc = Type.procedureType(info);
  974. if (proc instanceof Procedure.Std)
  975. throw new Errors.Error(proc.description() + " cannot be referenced");
  976. var scope = d.scope();
  977. if (scope instanceof Scope.Procedure)
  978. throw new Errors.Error("local procedure '" + d.code() + "' cannot be referenced");
  979. }
  980. var value;
  981. if (info instanceof Type.Const)
  982. value = Type.constValue(info);
  983. this.handleExpression(
  984. Code.makeExpression(d.code(), d.type(), d, value));
  985. },
  986. handleLogicalNot: function(){
  987. this.__logicalNot = !this.__logicalNot;
  988. this.setType(basicTypes.bool);
  989. },
  990. handleOperator: function(o){this.__operator = o;},
  991. handleConst: function(type, value, code){
  992. this.handleExpression(Code.makeExpression(
  993. code, type, undefined, value));
  994. },
  995. handleFactor: function(e){
  996. this.handleExpression(e);
  997. },
  998. endParse: function(){this.parent().handleTerm(this.__expression);},
  999. handleExpression: function(e){
  1000. promoteExpressionType(this, this.__expression, e);
  1001. if (this.__logicalNot){
  1002. e = op.not(e);
  1003. this.__logicalNot = false;
  1004. }
  1005. if (this.__operator)
  1006. e = this.__expression ? this.__operator(this.__expression, e)
  1007. : this.__operator(e);
  1008. this.__expression = e;
  1009. }
  1010. });
  1011. exports.Factor = ChainedContext.extend({
  1012. init: function FactorContext(context){
  1013. ChainedContext.prototype.init.call(this, context);
  1014. },
  1015. type: function(){return this.parent().type();},
  1016. handleLiteral: function(s){
  1017. var parent = this.parent();
  1018. if (s == "NIL")
  1019. parent.handleConst(nilType, undefined, "null");
  1020. else if (s == "TRUE")
  1021. parent.handleConst(basicTypes.bool, Code.makeIntConst(1), "true");
  1022. else if (s == "FALSE")
  1023. parent.handleConst(basicTypes.bool, Code.makeIntConst(0), "false");
  1024. else if (s == "~")
  1025. parent.handleLogicalNot();
  1026. },
  1027. handleFactor: function(e){this.parent().handleFactor(e);},
  1028. handleLogicalNot: function(){this.parent().handleLogicalNot();}
  1029. });
  1030. exports.Set = ChainedContext.extend({
  1031. init: function SetContext(context){
  1032. ChainedContext.prototype.init.call(this, context);
  1033. this.__value = 0;
  1034. this.__expr = "";
  1035. },
  1036. handleElement: function(from, fromValue, to, toValue){
  1037. if (fromValue && (!to || toValue)){
  1038. if (to)
  1039. for(var i = fromValue.value; i <= toValue.value; ++i)
  1040. this.__value |= 1 << i;
  1041. else
  1042. this.__value |= 1 << fromValue.value;
  1043. }
  1044. else{
  1045. if (this.__expr.length)
  1046. this.__expr += ", ";
  1047. if (to)
  1048. this.__expr += "[" + from + ", " + to + "]";
  1049. else
  1050. this.__expr += from;
  1051. }
  1052. },
  1053. endParse: function(){
  1054. var parent = this.parent();
  1055. if (!this.__expr.length)
  1056. parent.handleConst(basicTypes.set, Code.makeSetConst(this.__value), this.__value.toString());
  1057. else{
  1058. var code = this.language().rtl.makeSet(this.__expr);
  1059. if (this.__value)
  1060. code += " | " + this.__value;
  1061. var e = Code.makeExpression(code, basicTypes.set);
  1062. parent.handleFactor(e);
  1063. }
  1064. }
  1065. });
  1066. exports.SetElement = ChainedContext.extend({
  1067. init: function SetElementContext(context){
  1068. ChainedContext.prototype.init.call(this, context);
  1069. this.__from = undefined;
  1070. this.__fromValue = undefined;
  1071. this.__to = undefined;
  1072. this.__toValue = undefined;
  1073. this.__expr = Code.makeSimpleGenerator();
  1074. },
  1075. codeGenerator: function(){return this.__expr;},
  1076. handleExpression: function(e){
  1077. var value = e.constValue();
  1078. if (!this.__from)
  1079. {
  1080. this.__from = this.__expr.result();
  1081. this.__fromValue = value;
  1082. this.__expr = Code.makeSimpleGenerator();
  1083. }
  1084. else{
  1085. this.__to = this.__expr.result();
  1086. this.__toValue = value;
  1087. }
  1088. },
  1089. endParse: function(){
  1090. this.parent().handleElement(this.__from, this.__fromValue, this.__to, this.__toValue);
  1091. }
  1092. });
  1093. function constValueCode(value){
  1094. if (typeof value == "string")
  1095. return escapeString(value);
  1096. return value.toString();
  1097. }
  1098. exports.SimpleExpression = ChainedContext.extend({
  1099. init: function SimpleExpressionContext(context){
  1100. ChainedContext.prototype.init.call(this, context);
  1101. this.__unaryOperator = undefined;
  1102. this.__binaryOperator = undefined;
  1103. this.__type = undefined;
  1104. this.__exp = undefined;
  1105. },
  1106. handleTerm: function(e){
  1107. var type = e.type();
  1108. this.setType(type);
  1109. var o;
  1110. switch(this.__unaryOperator){
  1111. case "-":
  1112. o = assertNumericOrSetOp(type, this.__unaryOperator, op.negateReal, op.negateInt, op.setComplement);
  1113. break;
  1114. case "+":
  1115. o = assertNumericOp(type, this.__unaryOperator, op.unaryPlus);
  1116. break;
  1117. }
  1118. if (o){
  1119. this.__exp = o(e);
  1120. this.__unaryOperator = undefined;
  1121. }
  1122. else
  1123. this.__exp = this.__exp ? this.__binaryOperator(this.__exp, e) : e;
  1124. },
  1125. handleLiteral: function(s){this.__unaryOperator = s;},
  1126. type: function(){return this.__type;},
  1127. setType: function(type){
  1128. if (type === undefined || this.__type === undefined)
  1129. this.__type = type;
  1130. else
  1131. checkImplicitCast(this.language().types, type, this.__type);
  1132. },
  1133. handleBinaryOperator: function(o){this.__binaryOperator = o;},
  1134. endParse: function(){
  1135. this.parent().handleSimpleExpression(this.__exp);
  1136. }
  1137. });
  1138. exports.Expression = ChainedContext.extend({
  1139. init: function ExpressionContext(context, relOps){
  1140. ChainedContext.prototype.init.call(this, context);
  1141. this.__relOps = relOps || relationOps;
  1142. this.__relation = undefined;
  1143. this.__expression = undefined;
  1144. },
  1145. handleSimpleExpression: function(e){
  1146. if (!this.__expression){
  1147. this.__expression = e;
  1148. return;
  1149. }
  1150. var leftExpression = this.__expression;
  1151. var rightExpression = e;
  1152. leftExpression = promoteTypeInExpression(leftExpression, rightExpression.type());
  1153. rightExpression = promoteTypeInExpression(rightExpression, leftExpression.type());
  1154. var o = relationOp(leftExpression.type(), rightExpression.type(), this.__relation, this.__relOps, this);
  1155. this.__expression = o(leftExpression, rightExpression, this.language().rtl);
  1156. },
  1157. handleLiteral: function(relation){
  1158. this.__relation = relation;
  1159. },
  1160. codeGenerator: function(){return nullCodeGenerator;},
  1161. endParse: function(){
  1162. var type = this.__expression.type();
  1163. if (!type)
  1164. throw new Errors.Error("procedure returning no result cannot be used in an expression");
  1165. var parent = this.parent();
  1166. parent.codeGenerator().write(this.__expression.code());
  1167. parent.handleExpression(this.__expression);
  1168. }
  1169. });
  1170. function handleIfExpression(e){
  1171. var type = e.type();
  1172. if (type !== basicTypes.bool)
  1173. throw new Errors.Error("'BOOLEAN' expression expected, got '" + type.description() + "'");
  1174. }
  1175. /*
  1176. var IfContextBase = ChainedContext.extend({
  1177. init: function(context){
  1178. ChainedContext.prototype.init.call(this, context);
  1179. },
  1180. endParse: function(){
  1181. var gen = this.codeGenerator();
  1182. gen.write(")");
  1183. gen.openScope();
  1184. },
  1185. handleExpression: handleIfExpression
  1186. });
  1187. */
  1188. exports.If = ChainedContext.extend({
  1189. init: function IfContext(context){
  1190. ChainedContext.prototype.init.call(this, context);
  1191. this.codeGenerator().write("if (");
  1192. },
  1193. handleExpression: function(e){
  1194. handleIfExpression(e);
  1195. var gen = this.codeGenerator();
  1196. gen.write(")");
  1197. gen.openScope();
  1198. },
  1199. handleLiteral: function(s){
  1200. var gen = this.codeGenerator();
  1201. if (s == "ELSIF"){
  1202. gen.closeScope("");
  1203. gen.write("else if (");
  1204. }
  1205. else if (s == "ELSE"){
  1206. gen.closeScope("");
  1207. gen.write("else ");
  1208. gen.openScope();
  1209. }
  1210. },
  1211. endParse: function(){
  1212. this.codeGenerator().closeScope("");
  1213. }
  1214. });
  1215. exports.emitEndStatement = function(context){
  1216. context.codeGenerator().write(";\n");
  1217. };
  1218. exports.Case = ChainedContext.extend({
  1219. init: function CaseContext(context){
  1220. ChainedContext.prototype.init.call(this, context);
  1221. this.__type = undefined;
  1222. this.__firstCase = true;
  1223. this.genVarName("$c");
  1224. this.codeGenerator().write("$c = ");
  1225. },
  1226. handleExpression: function(e){
  1227. var type = e.type();
  1228. var gen = this.codeGenerator();
  1229. if (type instanceof Type.String){
  1230. var v;
  1231. if (Type.stringAsChar(type, {set: function(value){v = value;}})){
  1232. gen.write(v);
  1233. type = basicTypes.ch;
  1234. }
  1235. }
  1236. if (!Type.isInt(type) && type != basicTypes.ch)
  1237. throw new Errors.Error(
  1238. Type.intsDescription() + " or 'CHAR' expected as CASE expression");
  1239. this.__type = type;
  1240. gen.write(";\n");
  1241. },
  1242. beginCase: function(){
  1243. if (this.__firstCase)
  1244. this.__firstCase = false;
  1245. else
  1246. this.codeGenerator().write("else ");
  1247. },
  1248. handleLabelType: function(type){
  1249. if (!Cast.areTypesMatch(type, this.__type))
  1250. throw new Errors.Error(
  1251. "label must be '" + Type.typeName(this.__type) + "' (the same as case expression), got '"
  1252. + Type.typeName(type) + "'");
  1253. }
  1254. });
  1255. exports.CaseLabelList = ChainedContext.extend({
  1256. init: function CaseLabelListContext(context){
  1257. ChainedContext.prototype.init.call(this, context);
  1258. this.__glue = "";
  1259. },
  1260. handleLabelType: function(type){this.parent().handleLabelType(type);},
  1261. handleRange: function(from, to){
  1262. if (!this.__glue)
  1263. this.parent().caseLabelBegin();
  1264. var cond = to === undefined
  1265. ? "$c === " + from.value
  1266. : "($c >= " + from.value + " && $c <= " + to.value + ")";
  1267. this.codeGenerator().write(this.__glue + cond);
  1268. this.__glue = " || ";
  1269. },
  1270. endParse: function(){this.parent().caseLabelEnd();}
  1271. });
  1272. exports.CaseLabel = ChainedContext.extend({
  1273. init: function CaseLabelContext(context){
  1274. ChainedContext.prototype.init.call(this, context);
  1275. },
  1276. caseLabelBegin: function(){
  1277. this.parent().beginCase();
  1278. this.codeGenerator().write("if (");
  1279. },
  1280. caseLabelEnd: function(){
  1281. var gen = this.codeGenerator();
  1282. gen.write(")");
  1283. gen.openScope();
  1284. },
  1285. handleLabelType: function(type){this.parent().handleLabelType(type);},
  1286. handleRange: function(from, to){this.parent().handleRange(from, to);},
  1287. endParse: function(){this.codeGenerator().closeScope("");}
  1288. });
  1289. exports.CaseRange = ChainedContext.extend({
  1290. init: function CaseRangeContext(context){
  1291. ChainedContext.prototype.init.call(this, context);
  1292. this.__from = undefined;
  1293. this.__to = undefined;
  1294. },
  1295. codeGenerator: function(){return nullCodeGenerator;}, // suppress any output
  1296. handleLabel: function(type, v){
  1297. this.parent().handleLabelType(type);
  1298. if (this.__from === undefined )
  1299. this.__from = v;
  1300. else
  1301. this.__to = v;
  1302. },
  1303. handleConst: function(type, value){
  1304. if (type instanceof Type.String){
  1305. if (!Type.stringAsChar(type, {set: function(v){value = v;}}))
  1306. throw new Errors.Error("single-character string expected");
  1307. type = basicTypes.ch;
  1308. value = Code.makeIntConst(value);
  1309. }
  1310. this.handleLabel(type, value);
  1311. },
  1312. handleIdent: function(id){
  1313. var s = getSymbol(this.parent(), id);
  1314. if (!s.isConst())
  1315. throw new Errors.Error("'" + id + "' is not a constant");
  1316. var type = Type.constType(s.info());
  1317. if (type instanceof Type.String)
  1318. this.handleConst(type, undefined);
  1319. else
  1320. this.handleLabel(type, Type.constValue(s.info()));
  1321. },
  1322. endParse: function(){this.parent().handleRange(this.__from, this.__to);}
  1323. });
  1324. exports.While = ChainedContext.extend({
  1325. init: function WhileContext(context){
  1326. ChainedContext.prototype.init.call(this, context);
  1327. var gen = this.codeGenerator();
  1328. gen.write("while (true)");
  1329. gen.openScope();
  1330. gen.write("if (");
  1331. },
  1332. handleExpression: function WhileContext$handleExpression(e){
  1333. handleIfExpression(e);
  1334. var gen = this.codeGenerator();
  1335. gen.write(")");
  1336. gen.openScope();
  1337. },
  1338. handleLiteral: function(s){
  1339. if (s == "ELSIF"){
  1340. var gen = this.codeGenerator();
  1341. gen.closeScope("");
  1342. gen.write("else if (");
  1343. }
  1344. },
  1345. endParse: function(){
  1346. var gen = this.codeGenerator();
  1347. gen.closeScope(" else break;\n");
  1348. gen.closeScope("");
  1349. }
  1350. });
  1351. exports.Repeat = ChainedContext.extend({
  1352. init: function RepeatContext(context){
  1353. ChainedContext.prototype.init.call(this, context);
  1354. var gen = context.codeGenerator();
  1355. gen.write("do ");
  1356. gen.openScope();
  1357. }
  1358. });
  1359. exports.Until = ChainedContext.extend({
  1360. init: function UntilContext(context){
  1361. ChainedContext.prototype.init.call(this, context);
  1362. var gen = context.codeGenerator();
  1363. gen.closeScope(" while (");
  1364. },
  1365. handleExpression: handleIfExpression,
  1366. endParse: function(){this.codeGenerator().write(");\n");}
  1367. });
  1368. exports.For = ChainedContext.extend({
  1369. init: function ForContext(context){
  1370. ChainedContext.prototype.init.call(this, context);
  1371. this.__var = undefined;
  1372. this.__initExprParsed = false;
  1373. this.__toExpr = Code.makeSimpleGenerator();
  1374. this.__toParsed = false;
  1375. this.__by_parsed = false;
  1376. this.__by = undefined;
  1377. },
  1378. handleIdent: function(id){
  1379. var s = getSymbol(this.parent(), id);
  1380. if (!s.isVariable())
  1381. throw new Errors.Error("'" + s.id() + "' is not a variable");
  1382. var type = s.info().type();
  1383. if (type !== basicTypes.integer)
  1384. throw new Errors.Error(
  1385. "'" + s.id() + "' is a '"
  1386. + type.description() + "' variable, 'FOR' control variable must be 'INTEGER'");
  1387. this._handleInitCode(id, "for (" + id + " = ");
  1388. },
  1389. _handleInitCode: function(id, code){
  1390. this.__var = id;
  1391. this.codeGenerator().write(code);
  1392. },
  1393. _handleInitExpression: function(type){
  1394. if (type != basicTypes.integer)
  1395. throw new Errors.Error(
  1396. "'INTEGER' expression expected to assign '" + this.__var
  1397. + "', got '" + type.description() + "'");
  1398. this.__initExprParsed = true;
  1399. },
  1400. handleExpression: function(e){
  1401. var type = e.type();
  1402. if (!this.__initExprParsed)
  1403. this._handleInitExpression(type);
  1404. else if (!this.__toParsed) {
  1405. if (type != basicTypes.integer)
  1406. throw new Errors.Error(
  1407. "'INTEGER' expression expected as 'TO' parameter, got '" + type.description() + "'");
  1408. this.__toParsed = true;
  1409. }
  1410. else {
  1411. if (type != basicTypes.integer)
  1412. throw new Errors.Error("'INTEGER' expression expected as 'BY' parameter, got '" + type.description() + "'");
  1413. var value = e.constValue();
  1414. if ( value === undefined )
  1415. throw new Errors.Error("constant expression expected as 'BY' parameter");
  1416. this.__by = value.value;
  1417. }
  1418. },
  1419. codeGenerator: function(){
  1420. if (this.__initExprParsed && !this.__toParsed)
  1421. return this.__toExpr;
  1422. if (this.__toParsed && !this.__by_parsed)
  1423. return nullCodeGenerator; // suppress output for BY expression
  1424. return this.parent().codeGenerator();
  1425. },
  1426. handleBegin: function(){
  1427. this.__by_parsed = true;
  1428. var relation = this.__by < 0 ? " >= " : " <= ";
  1429. var step = this.__by === undefined
  1430. ? "++" + this.__var
  1431. : this.__var + (this.__by < 0
  1432. ? " -= " + -this.__by
  1433. : " += " + this.__by);
  1434. var s = "; " + this.__var + relation + this.__toExpr.result() + "; " + step + ")";
  1435. var gen = this.codeGenerator();
  1436. gen.write(s);
  1437. gen.openScope();
  1438. },
  1439. endParse: function(){this.codeGenerator().closeScope("");}
  1440. });
  1441. exports.emitForBegin = function(context){context.handleBegin();};
  1442. exports.CheckAssignment = ChainedContext.extend({
  1443. init: function Context$CheckAssignment(context){
  1444. ChainedContext.prototype.init.call(this, context);
  1445. },
  1446. handleLiteral: function(s){
  1447. if (s == "=")
  1448. throw new Errors.Error("did you mean ':=' (statement expected, got expression)?");
  1449. }
  1450. });
  1451. exports.ConstDecl = ChainedContext.extend({
  1452. init: function ConstDeclContext(context){
  1453. ChainedContext.prototype.init.call(this, context);
  1454. this.__id = undefined;
  1455. this.__type = undefined;
  1456. this.__value = undefined;
  1457. },
  1458. handleIdentdef: function(id){
  1459. this.__id = id;
  1460. this.codeGenerator().write("var " + id.id() + " = ");
  1461. },
  1462. handleExpression: function(e){
  1463. var value = e.constValue();
  1464. if (!value)
  1465. throw new Errors.Error("constant expression expected");
  1466. this.__type = e.type();
  1467. this.__value = value;
  1468. },
  1469. endParse: function(){
  1470. var c = Type.makeConst(this.__type, this.__value);
  1471. this.currentScope().addSymbol(Symbol.makeSymbol(this.__id.id(), c), this.__id.exported());
  1472. this.codeGenerator().write(";\n");
  1473. }
  1474. });
  1475. function checkIfFieldCanBeExported(name, idents, hint){
  1476. for(var i = 0; i < idents.length; ++i){
  1477. var id = idents[i];
  1478. if (!id.exported())
  1479. throw new Errors.Error(
  1480. "field '" + name + "' can be exported only if " + hint + " '" +
  1481. id.id() + "' itself is exported too");
  1482. }
  1483. }
  1484. exports.VariableDeclaration = HandleSymbolAsType.extend({
  1485. init: function Context$VariableDeclaration(context){
  1486. HandleSymbolAsType.prototype.init.call(this, context);
  1487. this.__idents = [];
  1488. this.__type = undefined;
  1489. },
  1490. handleIdentdef: function(id){this.__idents.push(id);},
  1491. exportField: function(name){
  1492. checkIfFieldCanBeExported(name, this.__idents, "variable");
  1493. },
  1494. setType: function(type){this.__type = type;},
  1495. type: function(){return this.__type;},
  1496. typeName: function(){return undefined;},
  1497. isAnonymousDeclaration: function(){return true;},
  1498. checkExport: function(){},
  1499. endParse: function(){
  1500. var v = Type.makeVariable(this.__type, false);
  1501. var idents = this.__idents;
  1502. var gen = this.codeGenerator();
  1503. for(var i = 0; i < idents.length; ++i){
  1504. var id = idents[i];
  1505. var varName = id.id();
  1506. if (id.exported())
  1507. this.checkExport(varName);
  1508. this.currentScope().addSymbol(Symbol.makeSymbol(varName, v), id.exported());
  1509. var t = v.type();
  1510. gen.write("var " + varName + " = " + t.initializer(this) + ";");
  1511. }
  1512. gen.write("\n");
  1513. }
  1514. });
  1515. exports.FieldListDeclaration = HandleSymbolAsType.extend({
  1516. init: function Context$FieldListDeclaration(context){
  1517. HandleSymbolAsType.prototype.init.call(this, context);
  1518. this.__idents = [];
  1519. this.__type = undefined;
  1520. },
  1521. typeName: function(){return undefined;},
  1522. handleIdentdef: function(id) {this.__idents.push(id);},
  1523. exportField: function(name){
  1524. checkIfFieldCanBeExported(name, this.__idents, "field");
  1525. },
  1526. setType: function(type) {this.__type = type;},
  1527. isAnonymousDeclaration: function(){return true;},
  1528. endParse: function(){
  1529. var idents = this.__idents;
  1530. var parent = this.parent();
  1531. for(var i = 0; i < idents.length; ++i)
  1532. parent.addField(idents[i], this.__type);
  1533. }
  1534. });
  1535. function assertProcType(type, info){
  1536. var unexpected;
  1537. if ( !type )
  1538. unexpected = info.idType();
  1539. else if (!(type instanceof Type.Procedure) && !(type instanceof Module.AnyType))
  1540. unexpected = type.description();
  1541. if (unexpected)
  1542. throw new Errors.Error("PROCEDURE expected, got '" + unexpected + "'");
  1543. return type;
  1544. }
  1545. function assertProcStatementResult(type){
  1546. if (type && !(type instanceof Module.AnyType))
  1547. throw new Errors.Error("procedure returning a result cannot be used as a statement");
  1548. }
  1549. function beginCallMsg(){}
  1550. function endCallMsg(){}
  1551. exports.ActualParameters = ChainedContext.extend({
  1552. init: function ActualParametersContext(context){
  1553. ChainedContext.prototype.init.call(this, context);
  1554. this.handleMessage(beginCallMsg);
  1555. },
  1556. handleLiteral: function(){}, // do not propagate ","
  1557. endParse: function(){
  1558. this.handleMessage(endCallMsg);
  1559. }
  1560. });
  1561. function isTypeRecursive(type, base){
  1562. if (type == base)
  1563. return true;
  1564. if (type instanceof Type.Record){
  1565. if (isTypeRecursive(Type.recordBase(type), base))
  1566. return true;
  1567. var fields = Type.recordOwnFields(type);
  1568. for(var fieldName in fields){
  1569. if (isTypeRecursive(fields[fieldName].type(), base))
  1570. return true;
  1571. }
  1572. }
  1573. else if (type instanceof Type.Array)
  1574. return isTypeRecursive(Type.arrayElementsType(type), base);
  1575. return false;
  1576. }
  1577. var RecordField = Type.Field.extend({
  1578. init: function Context$RecordField(identdef, type, recordType){
  1579. this.__identdef = identdef;
  1580. this.__type = type;
  1581. this.__refcordType = recordType;
  1582. },
  1583. id: function(){return this.__identdef.id();},
  1584. exported: function(){return this.__identdef.exported();},
  1585. identdef: function(){return this.__identdef;},
  1586. type: function(){return this.__type;},
  1587. recordType: function(){return this.__refcordType;}
  1588. });
  1589. exports.RecordDecl = ChainedContext.extend({
  1590. init: function RecordDeclContext(context, makeRecord){
  1591. ChainedContext.prototype.init.call(this, context);
  1592. var parent = this.parent();
  1593. var cons = parent.genTypeName();
  1594. var name = parent.isAnonymousDeclaration() ? "" : cons;
  1595. this.__type = makeRecord(name, cons, context.currentScope());
  1596. parent.setType(this.__type);
  1597. parent.codeGenerator().write("var " + cons + " = ");
  1598. },
  1599. type: function(){return this.__type;},
  1600. addField: function(field, type){
  1601. if (isTypeRecursive(type, this.__type))
  1602. throw new Errors.Error("recursive field definition: '"
  1603. + field.id() + "'");
  1604. this.__type.addField(new RecordField(field, type, this.__type));
  1605. if (field.exported())
  1606. this.parent().exportField(field.id());
  1607. },
  1608. setBaseType: function(type){
  1609. if (!(type instanceof Type.Record))
  1610. throw new Errors.Error(
  1611. "RECORD type is expected as a base type, got '"
  1612. + type.description()
  1613. + "'");
  1614. if (isTypeRecursive(type, this.__type))
  1615. throw new Errors.Error("recursive inheritance: '"
  1616. + Type.typeName(this.__type) + "'");
  1617. Type.setRecordBase(this.__type, type);
  1618. },
  1619. endParse: function(){
  1620. var type = this.__type;
  1621. var baseType = Type.recordBase(type);
  1622. var gen = this.codeGenerator();
  1623. var qualifiedBase = baseType ? this.qualifyScope(Type.recordScope(baseType)) + Type.typeName(baseType) : undefined;
  1624. gen.write((baseType ? qualifiedBase + ".extend"
  1625. : this.language().rtl.extendId())
  1626. + "(");
  1627. gen.openScope();
  1628. gen.write("init: function " + Type.recordConstructor(this.__type) + "()");
  1629. gen.openScope();
  1630. if (baseType)
  1631. gen.write(qualifiedBase + ".prototype.init.call(this);\n");
  1632. var ownFields = Type.recordOwnFields(type);
  1633. for(var f in ownFields)
  1634. gen.write("this." + f + " = " + ownFields[f].type().initializer(this) + ";\n");
  1635. gen.closeScope("");
  1636. gen.closeScope(");\n");
  1637. }
  1638. });
  1639. exports.TypeDeclaration = ChainedContext.extend({
  1640. init: function TypeDeclarationContext(context){
  1641. ChainedContext.prototype.init.call(this, context);
  1642. this.__id = undefined;
  1643. this.__symbol = undefined;
  1644. },
  1645. handleIdentdef: function(id){
  1646. var typeId = Type.makeLazyTypeId();
  1647. var symbol = Symbol.makeSymbol(id.id(), typeId);
  1648. this.currentScope().addSymbol(symbol, id.exported());
  1649. if (!id.exported())
  1650. this.currentScope().addFinalizer(function(){typeId.strip();});
  1651. this.__id = id;
  1652. this.__symbol = symbol;
  1653. },
  1654. setType: function(type){
  1655. Type.defineTypeId(this.__symbol.info(), type);
  1656. Scope.resolve(this.currentScope(), this.__symbol);
  1657. },
  1658. typeName: function(){return this.__id.id();},
  1659. genTypeName: function(){return this.__id.id();},
  1660. isAnonymousDeclaration: function(){return false;},
  1661. type: function(){return this.parent().type();},
  1662. exportField: function(name){
  1663. checkIfFieldCanBeExported(name, [this.__id], "record");
  1664. }
  1665. });
  1666. exports.TypeSection = ChainedContext.extend({
  1667. init: function TypeSection(context){
  1668. ChainedContext.prototype.init.call(this, context);
  1669. },
  1670. endParse: function(){
  1671. var unresolved = Scope.unresolved(this.currentScope());
  1672. if (unresolved.length)
  1673. throw new Errors.Error("no declaration found for '" + unresolved.join("', '") + "'");
  1674. }
  1675. });
  1676. exports.TypeCast = ChainedContext.extend({
  1677. init: function TypeCastContext(context){
  1678. ChainedContext.prototype.init.call(this, context);
  1679. this.__type = undefined;
  1680. },
  1681. handleQIdent: function(q){
  1682. var s = getQIdSymbolAndScope(this, q);
  1683. s = s.symbol();
  1684. if (!s.isType())
  1685. return; // this is not a type cast, may be procedure call
  1686. this.__type = s.info().type();
  1687. },
  1688. endParse: function(){
  1689. if (this.__type === undefined)
  1690. return false;
  1691. this.parent().handleTypeCast(this.__type);
  1692. return true;
  1693. }
  1694. });
  1695. exports.ModuleDeclaration = ChainedContext.extend({
  1696. init: function ModuleDeclarationContext(context){
  1697. ChainedContext.prototype.init.call(this, context);
  1698. this.__name = undefined;
  1699. this.__imports = {};
  1700. this.__moduleScope = undefined;
  1701. this.__moduleGen = undefined;
  1702. this.__stdSymbols = this.language().stdSymbols;
  1703. },
  1704. handleIdent: function(id){
  1705. var parent = this.parent();
  1706. if (this.__name === undefined ) {
  1707. this.__name = id;
  1708. this.__moduleScope = Scope.makeModule(id, this.__stdSymbols);
  1709. parent.pushScope(this.__moduleScope);
  1710. }
  1711. else if (id === this.__name){
  1712. var scope = parent.currentScope();
  1713. scope.close();
  1714. var exports = Scope.moduleExports(scope);
  1715. Scope.defineExports(Scope.moduleSymbol(scope).info(), exports);
  1716. this.codeGenerator().write(this.__moduleGen.epilog(exports));
  1717. }
  1718. else
  1719. throw new Errors.Error("original module name '" + this.__name + "' expected, got '" + id + "'" );
  1720. },
  1721. findModule: function(name){
  1722. if (name == this.__name)
  1723. throw new Errors.Error("module '" + this.__name + "' cannot import itself");
  1724. return this.parent().findModule(name);
  1725. },
  1726. handleImport: function(modules){
  1727. var scope = this.currentScope();
  1728. var moduleAliases = {};
  1729. for(var i = 0; i < modules.length; ++i){
  1730. var s = modules[i];
  1731. var name = Type.moduleName(s.info());
  1732. this.__imports[name] = s;
  1733. scope.addSymbol(s);
  1734. moduleAliases[name] = s.id();
  1735. }
  1736. this.__moduleGen = this.parent().makeModuleGenerator(
  1737. this.__name,
  1738. moduleAliases);
  1739. this.codeGenerator().write(this.__moduleGen.prolog());
  1740. },
  1741. qualifyScope: function(scope){
  1742. if (scope != this.__moduleScope && scope instanceof Scope.Module){
  1743. var id = Scope.moduleSymbol(scope).id();
  1744. return this.__imports[id].id() + ".";
  1745. }
  1746. return "";
  1747. }
  1748. });
  1749. var ModuleImport = ChainedContext.extend({
  1750. init: function ModuleImport(context){
  1751. ChainedContext.prototype.init.call(this, context);
  1752. this.__import = {};
  1753. this.__currentModule = undefined;
  1754. this.__currentAlias = undefined;
  1755. },
  1756. handleIdent: function(id){
  1757. this.__currentModule = id;
  1758. },
  1759. handleLiteral: function(s){
  1760. if (s == ":=")
  1761. this.__currentAlias = this.__currentModule;
  1762. else if (s == ",")
  1763. this.__handleImport();
  1764. },
  1765. endParse: function(){
  1766. if (this.__currentModule)
  1767. this.__handleImport();
  1768. var modules = [];
  1769. var unresolved = [];
  1770. for(var alias in this.__import){
  1771. var moduleName = this.__import[alias];
  1772. var module = this.parent().findModule(moduleName);
  1773. if (!module)
  1774. unresolved.push(moduleName);
  1775. else
  1776. modules.push(Symbol.makeSymbol(alias, module));
  1777. }
  1778. if (unresolved.length)
  1779. throw new Errors.Error("module(s) not found: " + unresolved.join(", "));
  1780. this.parent().handleImport(modules);
  1781. },
  1782. __handleImport: function(){
  1783. var alias = this.__currentAlias;
  1784. if (!alias)
  1785. alias = this.__currentModule;
  1786. else
  1787. this.__currentAlias = undefined;
  1788. for(var a in this.__import){
  1789. if (a == alias)
  1790. throw new Errors.Error("duplicated alias: '" + alias +"'");
  1791. if (this.__import[a] == this.__currentModule)
  1792. throw new Errors.Error("module already imported: '" + this.__currentModule +"'");
  1793. }
  1794. this.__import[alias] = this.__currentModule;
  1795. }
  1796. });
  1797. exports.ModuleImport = ModuleImport;
  1798. exports.Context = Class.extend({
  1799. init: function Context(language){
  1800. this.__language = language;
  1801. this.__scopes = [];
  1802. this.__gen = 0;
  1803. this.__vars = [];
  1804. },
  1805. language: function(){return this.__language;},
  1806. genTypeName: function(){
  1807. ++this.__gen;
  1808. return "anonymous$" + this.__gen;
  1809. },
  1810. genVarName: function(id){
  1811. if (this.__vars.indexOf(id) === -1) {
  1812. this.codeGenerator().write("var " + id + ";\n");
  1813. this.__vars.push(id);
  1814. }
  1815. },
  1816. findSymbol: function(ident){
  1817. for(var i = this.__scopes.length; i--;){
  1818. var scope = this.__scopes[i];
  1819. var s = scope.findSymbol(ident);
  1820. if (s)
  1821. return s;
  1822. }
  1823. return undefined;
  1824. },
  1825. currentScope: function(){return this.__scopes[this.__scopes.length - 1];},
  1826. pushScope: function(scope){this.__scopes.push(scope);},
  1827. popScope: function(){
  1828. var scope = this.__scopes.pop();
  1829. scope.close();
  1830. },
  1831. handleExpression: function(){},
  1832. handleLiteral: function(){},
  1833. codeGenerator: function(){return this.__language.codeGenerator;},
  1834. makeModuleGenerator: function(name, imports){
  1835. return this.__language.moduleGenerator(name, imports);
  1836. },
  1837. findModule: function(name){
  1838. if (name == "JS"){
  1839. return Module.makeJS();
  1840. }
  1841. return this.__language.moduleResolver ? this.__language.moduleResolver(name) : undefined;
  1842. }
  1843. });
  1844. function makeProcCall(context, type, info, code){
  1845. assertProcType(type, info);
  1846. var l = context.language();
  1847. return type.callGenerator(
  1848. { types: l.types,
  1849. rtl: l.rtl,
  1850. qualifyScope: context.qualifyScope.bind(context)
  1851. },
  1852. code);
  1853. }
  1854. exports.AddArgumentMsg = AddArgumentMsg;
  1855. exports.assertProcStatementResult = assertProcStatementResult;
  1856. exports.beginCallMsg = beginCallMsg;
  1857. exports.endCallMsg = endCallMsg;
  1858. exports.Chained = ChainedContext;
  1859. exports.endParametersMsg = endParametersMsg;
  1860. exports.getSymbolAndScope = getSymbolAndScope;
  1861. exports.IdentdefInfo = IdentdefInfo;
  1862. exports.makeProcCall = makeProcCall;
  1863. exports.unwrapType = unwrapType;
  1864. exports.IdentdefInfo = IdentdefInfo;
  1865. exports.RecordField = RecordField;
  1866. exports.RelationOps = RelationOps;