ScummVM API documentation
lingo.h
1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21 
22 #ifndef DIRECTOR_LINGO_LINGO_H
23 #define DIRECTOR_LINGO_LINGO_H
24 
25 namespace Audio {
26 class AudioStream;
27 }
28 namespace Common {
29 class SeekableReadStreamEndian;
30 }
31 
32 namespace Director {
33 
34 struct ChunkReference;
35 struct MenuReference;
36 struct PictureReference;
37 struct TheEntity;
38 struct TheEntityField;
39 struct LingoArchive;
40 struct LingoV4Bytecode;
41 struct LingoV4TheEntity;
42 struct Node;
43 struct Picture;
44 class AbstractObject;
45 class Cast;
46 class ScriptContext;
47 class DirectorEngine;
48 class Frame;
49 class LingoCompiler;
50 struct Breakpoint;
51 
52 typedef void (*inst)(void);
53 #define STOP (inst)0
54 #define ENTITY_INDEX(t,id) ((t) * 100000 + (id))
55 
56 int calcStringAlignment(const char *s);
57 int calcCodeAlignment(int l);
58 
59 typedef Common::Array<inst> ScriptData;
60 
61 struct FuncDesc {
62  Common::String name;
63  const char *proto;
64 
65  FuncDesc(Common::String n, const char *p) { name = n; proto = p; }
66 };
67 
69 
71 
72 struct BuiltinProto {
73  const char *name;
74  void (*func)(int);
75  int minArgs; // -1 -- arglist
76  int maxArgs;
77  int version;
78  SymbolType type;
79 };
80 
81 struct Symbol { /* symbol table entry */
82  Common::String *name;
83  SymbolType type;
84  union {
85  ScriptData *defn; /* HANDLER */
86  void (*func)(); /* OPCODE */
87  void (*bltin)(int); /* BUILTIN */
88  Common::String *s; /* STRING */
89  } u;
90 
91  int *refCount;
92 
93  int nargs; /* number of arguments */
94  int maxArgs; /* maximal number of arguments, for builtins */
95  int targetType; /* valid target objects, for method builtins */
96 
99  ScriptContext *ctx; /* optional script context to execute with */
100  AbstractObject *target; /* optional method target */
101  bool anonymous;
102 
103  Symbol();
104  Symbol(const Symbol &s);
105  Symbol& operator=(const Symbol &s);
106  bool operator==(Symbol &s) const;
107  void reset();
108  ~Symbol();
109 };
110 
111 struct PArray {
112  bool _sorted;
113  PropertyArray arr;
114 
115  PArray() : _sorted(false) {}
116 
117  PArray(int size) : _sorted(false), arr(size) {}
118 };
119 
120 struct FArray {
121  bool _sorted;
122  DatumArray arr;
123 
124  FArray() : _sorted(false) {}
125 
126  FArray(int size) : _sorted(false), arr(size) {}
127 };
128 
129 
130 struct Datum { /* interpreter stack type */
131  DatumType type;
132 
133  union {
134  int i; /* INT, ARGC, ARGCNORET */
135  double f; /* FLOAT */
136  Common::String *s; /* STRING, VARREF, OBJECT */
137  FArray *farr; /* ARRAY, POINT, RECT */
138  PArray *parr; /* PARRAY */
139  AbstractObject *obj; /* OBJECT */
140  ChunkReference *cref; /* CHUNKREF */
141  CastMemberID *cast; /* CASTREF, FIELDREF */
142  MenuReference *menu; /* MENUREF */
143  PictureReference *picture; /* PICTUREREF */
144  } u;
145 
146  int *refCount;
147 
148  bool ignoreGlobal; // True if this Datum should be ignored by showGlobals and clearGlobals
149 
150  Datum();
151  Datum(const Datum &d);
152  Datum& operator=(const Datum &d);
153  Datum(int val);
154  Datum(double val);
155  Datum(const Common::String &val);
156  Datum(AbstractObject *val);
157  Datum(const CastMemberID &val);
158  Datum(const Common::Point &point);
159  Datum(const Common::Rect &rect);
160  void reset();
161 
162  ~Datum() {
163  reset();
164  }
165 
166  Datum eval() const;
167  double asFloat() const;
168  int asInt() const;
169  Common::String asString(bool printonly = false) const;
170  CastMemberID asMemberID(CastType castType = kCastTypeAny, int castLib = 0) const;
171  Common::Point asPoint() const;
172  Datum clone() const;
173 
174  bool isRef() const;
175  bool isVarRef() const;
176  bool isCastRef() const;
177  bool isArray() const;
178  bool isNumeric() const;
179 
180  const char *type2str(bool ilk = false) const;
181 
182  int equalTo(Datum &d, bool ignoreCase = false) const;
183  uint32 compareTo(Datum &d) const;
184 
185  bool operator==(Datum &d) const;
186  bool operator>(Datum &d) const;
187  bool operator<(Datum &d) const;
188  bool operator>=(Datum &d) const;
189  bool operator<=(Datum &d) const;
190 };
191 
193  Datum source;
194  ChunkType type;
195  int startChunk;
196  int endChunk;
197  int start;
198  int end;
199 
200  ChunkReference(const Datum &src, ChunkType t, int sc, int ec, int s, int e)
201  : source(src), type(t), startChunk(sc), endChunk(ec), start(s), end(e) {}
202 };
203 
205  int menuIdNum;
206  Common::String *menuIdStr;
207  int menuItemIdNum;
208  Common::String *menuItemIdStr;
209 
210  MenuReference();
211 };
212 
214  Picture *_picture = nullptr;
215  ~PictureReference();
216 };
217 
218 struct PCell {
219  Datum p;
220  Datum v;
221 
222  PCell();
223  PCell(const Datum &prop, const Datum &val);
224 };
225 
226 struct Builtin {
227  void (*func)(void);
228  int nargs;
229 
230  Builtin(void (*func1)(void), int nargs1) : func(func1), nargs(nargs1) {}
231 };
232 
240 typedef void (*XLibOpenerFunc)(ObjectType, const Common::Path &);
241 typedef void (*XLibCloserFunc)(ObjectType);
246 
249 
250 struct CFrame { /* proc/func call stack frame */
251  Symbol sp; /* symbol table entry */
252  int retPC; /* where to resume after return */
253  ScriptData *retScript; /* which script to resume after return */
254  ScriptContext *retContext; /* which script context to use after return */
255  DatumHash *retLocalVars;
256  Datum retMe; /* which me obj to use after return */
257  uint stackSizeBefore;
258  bool allowRetVal; /* whether to allow a return value */
259  Datum defaultRetVal; /* default return value */
260  int paramCount; /* original number of arguments submitted */
261  Common::Array<Datum> paramList; /* original argument list */
262 };
263 
264 struct LingoEvent {
265  LEvent event;
266  int eventId;
267  EventHandlerSourceType eventHandlerSourceType;
268  ScriptType scriptType;
269  bool passByDefault;
270  uint16 channelId;
271  CastMemberID scriptId;
272  Common::Point mousePos;
273 
274  LingoEvent (LEvent e, int ei, ScriptType st, bool pass, CastMemberID si = CastMemberID(), Common::Point mp = Common::Point(-1, -1)) {
275  event = e;
276  eventId = ei;
277  eventHandlerSourceType = kNoneHandler;
278  scriptType = st;
279  passByDefault = pass;
280  channelId = 0;
281  scriptId = si;
282  mousePos = mp;
283  }
284 
285  LingoEvent (LEvent e, int ei, EventHandlerSourceType ehst, bool pass, Common::Point mp = Common::Point(-1, -1)) {
286  event = e;
287  eventId = ei;
288  eventHandlerSourceType = ehst;
289  scriptType = kNoneScript;
290  passByDefault = pass;
291  channelId = 0;
292  scriptId = CastMemberID();
293  mousePos = mp;
294  }
295 };
296 
297 
298 struct LingoArchive {
299  LingoArchive(Cast *c) : cast(c) {};
300  ~LingoArchive();
301 
302  Cast *cast;
303  ScriptContextHash lctxContexts;
304  ScriptContextHash scriptContexts[kMaxScriptType + 1];
305  FactoryContextHash factoryContexts;
307  Common::HashMap<uint32, Common::String> primaryEventHandlers;
308  SymbolHash functionHandlers;
309 
310  ScriptContext *getScriptContext(ScriptType type, uint16 id);
311  ScriptContext *findScriptContext(uint16 id);
312  Common::String getName(uint16 id);
313  Common::String formatFunctionList(const char *prefix);
314 
315  void addCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr, uint32 preprocFlags = kLPPNone);
316  void patchCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr, uint32 preprocFlags = kLPPNone);
317  void removeCode(ScriptType type, uint16 id);
318  void replaceCode(const Common::U32String &code, ScriptType type, uint16 id, const char *scriptName = nullptr);
319  void addCodeV4(Common::SeekableReadStreamEndian &stream, uint16 lctxIndex, const Common::String &archName, uint16 version);
320  void addNamesV4(Common::SeekableReadStreamEndian &stream);
321 
322  // lingo-patcher.cpp
323  void patchScriptHandler(ScriptType type, CastMemberID id);
324 };
325 
326 struct LingoState {
327  // Execution state for a Lingo process, created every time
328  // a top-level handler is called (e.g. on mouseDown).
329  // Can be swapped out when another script gets called with priority.
330  // Call frames are pushed and popped from the callstack with
331  // pushContext and popContext.
332  Common::Array<CFrame *> callstack; // call stack
333  uint pc = 0; // current program counter
334  ScriptData *script = nullptr; // current Lingo script
335  ScriptContext *context = nullptr; // current Lingo script context
336  DatumHash *localVars = nullptr; // current local variables
337  Datum me; // current me object
338 
339  ~LingoState();
340 };
341 
342 enum LingoExecState {
343  kRunning,
344  kPause,
345 };
346 
347 class Lingo {
348 
349 public:
350  Lingo(DirectorEngine *vm);
351  ~Lingo();
352 
353  void resetLingo();
354  void cleanupLingo();
355  void resetLingoGo();
356 
357  int getMenuNum();
358  int getMenuItemsNum(Datum &d);
359  int getXtrasNum();
360  int getCastLibsNum();
361  int getMembersNum();
362 
363  void executeHandler(const Common::String &name);
364  void executeScript(ScriptType type, CastMemberID id);
365  Common::String formatStack();
366  void printStack(const char *s, uint pc);
367  Common::String formatCallStack(uint pc);
368  void printCallStack(uint pc);
369  Common::String formatFrame();
370  Common::String formatCurrentInstruction();
371  Common::String decodeInstruction(ScriptData *sd, uint pc, uint *newPC = NULL);
372  Common::String decodeScript(ScriptData *sd);
373  Common::String formatFunctionName(Symbol &sym);
374  Common::String formatFunctionBody(Symbol &sym);
375 
376  void reloadBuiltIns();
377  void initBuiltIns();
378  void initBuiltIns(const BuiltinProto protos[]);
379  void cleanupBuiltIns();
380  void cleanupBuiltIns(const BuiltinProto protos[]);
381  void initFuncs();
382  void cleanupFuncs();
383  void initBytecode();
384  void initMethods();
385  void cleanupMethods();
386  void initXLibs();
387  void cleanupXLibs();
388 
389  Common::String normalizeXLibName(Common::String name);
390  void openXLib(Common::String name, ObjectType type, const Common::Path &path);
391  void closeXLib(Common::String name);
392  void closeOpenXLibs();
393  void reloadOpenXLibs();
394 
395  void runTests();
396 
397  // lingo-events.cpp
398 private:
399  void initEventHandlerTypes();
400  bool processEvent(LEvent event, ScriptType st, CastMemberID scriptId, int channelId = -1);
401 
402 public:
403  ScriptType event2script(LEvent ev);
404  Symbol getHandler(const Common::String &name);
405 
406  void processEvents(Common::Queue<LingoEvent> &queue, bool isInputEvent);
407 
408 public:
409  bool execute();
410  void switchStateFromWindow();
411  void freezeState();
412  void freezePlayState();
413  void pushContext(const Symbol funcSym, bool allowRetVal, Datum defaultRetVal, int paramCount, int nargs);
414  void popContext(bool aborting = false);
415  void cleanLocalVars();
416  void varAssign(const Datum &var, const Datum &value);
417  Datum varFetch(const Datum &var, bool silent = false);
418  Common::U32String evalChunkRef(const Datum &var);
419  Datum findVarV4(int varType, const Datum &id);
420  CastMemberID resolveCastMember(const Datum &memberID, const Datum &castLib, CastType type);
421  void exposeXObject(const char *name, Datum obj);
422 
423  int getAlignedType(const Datum &d1, const Datum &d2, bool equality);
424 
425  Common::String formatAllVars();
426  void printAllVars();
427 
428  inst readInst() { return getInst(_state->pc++); }
429  inst getInst(uint pc) { return (*_state->script)[pc]; }
430  int readInt() { return getInt(_state->pc++); }
431  int getInt(uint pc);
432  double readFloat() { double d = getFloat(_state->pc); _state->pc += calcCodeAlignment(sizeof(double)); return d; }
433  double getFloat(uint pc) { return *(double *)(&((*_state->script)[_state->pc])); }
434  char *readString() { char *s = getString(_state->pc); _state->pc += calcStringAlignment(s); return s; }
435  char *getString(uint pc) { return (char *)(&((*_state->script)[_state->pc])); }
436 
437  Datum getVoid();
438  void pushVoid();
439 
440  void printArgs(const char *funcname, int nargs, const char *prefix = nullptr);
441  inline void printSTUBWithArglist(const char *funcname, int nargs) { printArgs(funcname, nargs, "STUB: "); }
442  void convertVOIDtoString(int arg, int nargs);
443  void dropStack(int nargs);
444  void drop(uint num);
445 
446  void lingoError(const char *s, ...);
447 
448  void func_mci(const Common::String &name);
449  void func_mciwait(const Common::String &name);
450  void func_beep(int repeats);
451  void func_goto(Datum &frame, Datum &movie, bool commandgo = false );
452  void func_gotoloop();
453  void func_gotonext();
454  void func_gotoprevious();
455  void func_play(Datum &frame, Datum &movie);
456  void func_playdone();
457  void func_cursor(Datum cursorDatum);
458  int func_marker(int m);
459  uint16 func_label(Datum &label);
460 
461  // lingo-the.cpp
462 public:
463  void initTheEntities();
464  void cleanUpTheEntities();
465  const char *entity2str(int id);
466  const char *field2str(int id);
467 
468  // global kTheEntity
469  Datum _actorList;
470  Common::u32char_type_t _itemDelimiter;
471  bool _exitLock;
472  bool _preLoadEventAbort; // no-op, everything is always preloaded
473  Datum _searchPath;
474  bool _trace; // state of movie's trace function
475  int _traceLoad; // internal Director verbosity level
476  bool _updateMovieEnabled;
477  bool _romanLingo;
478 
479  Datum getTheEntity(int entity, Datum &id, int field);
480  void setTheEntity(int entity, Datum &id, int field, Datum &d);
481  Datum getTheSprite(Datum &id, int field);
482  void setTheSprite(Datum &id, int field, Datum &d);
483  Datum getTheCast(Datum &id, int field);
484  void setTheCast(Datum &id, int field, Datum &d);
485  Datum getTheField(Datum &id1, int field);
486  void setTheField(Datum &id1, int field, Datum &d);
487  Datum getTheChunk(Datum &chunk, int field);
488  void setTheChunk(Datum &chunk, int field, Datum &d);
489  void getObjectProp(Datum &obj, Common::String &propName);
490  void setObjectProp(Datum &obj, Common::String &propName, Datum &d);
491  Datum getTheDate(int field);
492  Datum getTheTime(int field);
493  Datum getTheDeskTopRectList();
494 
495 private:
496  Common::StringArray _entityNames;
497  Common::StringArray _fieldNames;
498 
499 public:
500  LingoCompiler *_compiler;
501  LingoState *_state;
502 
503  int _currentChannelId;
504 
505  bool _freezeState;
506  bool _freezePlay;
507  bool _playDone;
508  bool _abort;
509  bool _expectError;
510  bool _caughtError;
511 
512  TheEntityHash _theEntities;
513  TheEntityFieldHash _theEntityFields;
514 
515  int _objectEntityId;
516 
517  SymbolHash _builtinCmds;
518  SymbolHash _builtinFuncs;
519  SymbolHash _builtinConsts;
520  SymbolHash _builtinListHandlers;
521  SymbolHash _methods;
522  XLibOpenerFuncHash _xlibOpeners;
523  XLibCloserFuncHash _xlibClosers;
524 
525  OpenXLibsHash _openXLibs;
526  OpenXLibsStateHash _openXLibsState;
527  Common::StringArray _openXtras;
528 
529  Common::String _floatPrecisionFormat;
530 
531 public:
532  void push(Datum d);
533  Datum pop();
534  Datum peek(uint offset);
535 
536 public:
537  Common::HashMap<uint32, const char *> _eventHandlerTypes;
540 
541  DatumHash _globalvars;
542 
543  FuncHash _functions;
544 
547 
548  uint _globalCounter;
549 
550  StackData _stack;
551 
552  DirectorEngine *_vm;
553 
554  int _floatPrecision;
555 
556  Datum _theResult;
557 
558  // events
559  bool _passEvent;
560  Datum _perFrameHook;
561 
562  Datum _windowList;
563  Symbol _currentInputEvent;
564 
565  struct {
566  LingoExecState _state = kRunning;
567  bool (*_shouldPause)() = nullptr;
568  } _exec;
569 
570 public:
571  void executeImmediateScripts(Frame *frame);
572  void executePerFrameHook(int frame, int subframe);
573 
574  // lingo-utils.cpp
575 private:
576  Common::HashMap<uint32, Common::U32String> _charNormalizations;
577  void initCharNormalizations();
578 
579 public:
580  Common::String normalizeString(const Common::String &str);
581 
582 public:
583  void addBreakpoint(Breakpoint &bp);
584  bool delBreakpoint(int id);
585  Breakpoint *getBreakpoint(int id);
586 
587  const Common::Array<Breakpoint> &getBreakpoints() const { return _breakpoints; }
588  Common::Array<Breakpoint> &getBreakpoints() { return _breakpoints; }
589 
590 private:
591  int _bpNextId = 1;
592  Common::Array<Breakpoint> _breakpoints;
593 };
594 
595 extern Lingo *g_lingo;
596 
597 } // End of namespace Director
598 
599 #endif
Definition: lingo.h:111
Definition: cast.h:85
Definition: lingo.h:81
Definition: str.h:59
Definition: lingo.h:298
Definition: lingo.h:61
Definition: lingo.h:120
Definition: array.h:52
Definition: picture.h:33
Definition: lingo.h:250
Definition: rect.h:144
Definition: path.h:52
Definition: lingo.h:264
Definition: lingo.h:192
Definition: archive.h:35
Definition: queue.h:42
Definition: lingo.h:213
Definition: lingo.h:226
Definition: ustr.h:57
Definition: algorithm.h:29
Definition: rect.h:45
Definition: lingo-codegen.h:30
Definition: lingo.h:130
char32_t u32char_type_t
Definition: ustr.h:41
Definition: lingo.h:204
Definition: debugger.h:45
Definition: stream.h:944
Definition: director.h:150
Definition: lingo.h:72
Definition: lingo-object.h:42
Definition: lingo.h:218
Definition: lobject.h:332
Definition: frame.h:151
Definition: lingo.h:347
Definition: types.h:414
Definition: system.h:38
Definition: lingo-object.h:213
Definition: lingo.h:326