1 // idlc.h -- Definitions used throughout idlc.
2 // A lot of this should probably be factored out into more specific headers.
4 // This software is copyright (c) 2006 Scott Wood <scott@buserror.net>.
6 // This software is provided 'as-is', without any express or implied warranty.
7 // In no event will the authors or contributors be held liable for any damages
8 // arising from the use of this software.
10 // Permission is hereby granted to everyone, free of charge, to use, copy,
11 // modify, prepare derivative works of, publish, distribute, perform,
12 // sublicense, and/or sell copies of the Software, provided that the above
13 // copyright notice and disclaimer of warranty be included in all copies or
14 // substantial portions of this software.
19 // inttypes.h on OSX assumes it can use restrict, but C++ doesn't have it.
20 // Hopefully C++ will catch up to C soon...
34 #include "compileddef.h"
45 #define cdl_lex idl_lex
46 void idl_error(const char *s);
48 #define cdl_error idl_error
50 void setup_idlparse();
51 void setup_cdlparse();
54 void yyerrorf(const char *s, ...) __attribute__((format(printf, 1, 2)));
55 void yyerrorfl(const char *file, int line, const char *s, ...)
56 __attribute__((format(printf, 3, 4)));
58 void yyerrorf(const char *s, ...);
59 void yyerrorfl(const char *file, int line, const char *s, ...);
66 extern int idl_debug, cdl_debug, curline, impl, num_err;
67 extern int current_pass;
69 extern unsigned int enum_pos;
70 extern const char *cur_input_file;
71 extern int compiling_idl, compiling_cdl;
76 // Location in the IDLC source of the BUG()
80 InternalError(const char *file, int line) :
81 file(file), line(line)
87 throw InternalError(__FILE__, __LINE__); \
92 #define assert(x) do { \
100 virtual ~Releasable()
104 Releasable(int COUNT) : count(COUNT)
111 fprintf(stderr, "Reference count is %d in release\n", count);
120 class AutoReleasePool {
121 list<const Releasable *> pool;
124 void add(const Releasable *obj)
131 for (list<const Releasable *>::iterator i = pool.begin();
132 i != pool.end(); ++i)
134 const Releasable *obj = *i;
142 extern AutoReleasePool autorelease_pool;
144 template <typename T>
145 class RefCountable : public Releasable {
147 // RefCountable objects should never be assigned to,
148 // as there could be references to the object remaining.
149 // The private assignment operator prevents this, unless
150 // a subclass defines its own assigment operator (don't
152 void operator =(const RefCountable &rc)
157 RefCountable(const RefCountable &rc) : Releasable(1)
163 RefCountable() : Releasable(1)
165 // Normally, this wouldn't be automatic, but this is what most
166 // things in IDLC are going to want, and it elimanates problems
167 // with needing to cast the return type of autorelease().
169 // The automatic autorelease() means that all refcountable objects
170 // must be allocated with "new", not on the stack, as global
171 // data, or as a class member.
176 virtual ~RefCountable()
180 const T *retain() const
183 fprintf(stderr, "Reference count is %d in retain\n", count);
188 return static_cast<const T *>(this);
194 fprintf(stderr, "Reference count is %d in retain\n", count);
199 return static_cast<T *>(this);
202 const T *autorelease() const
204 autorelease_pool.add(static_cast<Releasable *>(this));
205 return static_cast<T *>(this);
210 autorelease_pool.add(static_cast<Releasable *>(this));
211 return static_cast<T *>(this);
214 // This is only here because C++ obnoxiously requires it to
215 // be just because it's "called" from code excluded with an
216 // if (0) in a template. No code is ever generated that calls
217 // it, but it still must exist.
219 bool operator < (const RefCountable &rc)
225 // T must be RefCountable
226 template<typename T, bool compare_ptrs = true>
228 // STL containers like to use const on the items they
229 // contain; the mutable allows such containers to hold
230 // pointers to non-const data. For truly const Refs,
231 // make T const, as in StringRef. Unfortunately,
232 // it cannot be done in a more fine-grained manner,
244 Ref(T *data) : data(data)
250 Ref(Ref &le) : data(le.data)
256 Ref &operator =(const Ref &le)
258 // The retain must come first, in case both Refs are the same
269 Ref &operator =(T *new_data)
271 // The retain must come first, in case both Refs are the same
298 T *operator *() const
303 T *operator ->() const
308 bool operator == (const Ref &le) const
311 return data == le.data;
313 return *data == *le.data;
316 bool operator != (const Ref &le) const
319 return data != le.data;
321 return *data != *le.data;
324 bool operator < (const Ref &le) const
327 return reinterpret_cast<intptr_t>(data) <
328 reinterpret_cast<intptr_t>(le.data);
330 return *data < *le.data;
334 class String : public string, public RefCountable<String> {
336 // Origin of the string, if from the IDL file.
337 // Otherwise, fill both values with zero.
343 String(const char *s = "") : string(s)
350 String(const String &s) : string(s)
357 String(const char *s, const char *file, int line, int token) :
358 string(s), file(file), line(line), token(token)
362 extern String **yylval_string;
363 typedef Ref<const String, false> StringRef;
365 /* If a StrList is used for a namespace-qualified identifier, and
366 said identifier begins with ".." (i.e. starts from the root
367 namespace), the leading ".." is represented by a zero-length
370 Note that list doesn't have a virtual destructor, so all deletions
371 should happen through either RefCountable or the wrapper List
374 class StrList : public list<StringRef>, public RefCountable<StrList> {
380 // Parse a flat String into a StrList, using the specified delimeter.
381 StrList(const String *input, char delimiter = '.');
383 // Turn a StrList into a flat String, using the specified delimiter.
384 String *flatten(const char *delimiter = ".");
387 typedef Ref<StrList> StrListRef;
389 // ConList is like StrList, but with constant initializers
399 // FIXME: handle platforms with weird floating point endianness
405 // TOK_ICON, TOK_UCON, TOK_FCON, TOK_BOOL, TOK_DCON,
406 // TOK_INVALID, or TOK_NONE
407 // Constants are stored as signed (ICON) unless too
408 // large to fit in a signed 64-bit integer. Additional size and
409 // signedness checks are mode when down casting to a smaller size
410 // to fit into a particular datum; such constants will have a
413 // TOK_NONE is valid for maybeconst and size. TOK_INVALID
414 // indicates a previously detected error; don't emit any further
415 // errors due to this constant.
417 // TOK_DCON is used for symbolic constants, whose value may
423 extern Con *yylval_con;
429 ConInit(const String *str, Con &con) : str(str), con(con)
433 ConInit(const ConInit &coninit)
439 class ConList : public list<ConInit>, public RefCountable<ConList> {};
440 typedef Ref<ConList> ConListRef;
442 // Like StrList, but is a list of possibly namespace-qualified identifiers.
443 class IDList : public list<StrListRef>, public RefCountable<IDList> {};
444 typedef Ref<IDList> IDListRef;
450 // This is incremented when a chain of symbols is traversed to reset
451 // detection of already-visited symbols. It is assumed that this
452 // will not have to happen billions of times.
454 extern int traversal;
456 class Symbol : public RefCountable<Symbol> {
470 // Symbol was loaded externally
473 // If set, the symbol is private, and will not be available
474 // for lookups except those made directly in the context of
475 // the containing namespace. Private symbols do not get
476 // outputted. They are used to implement imports of specific
477 // symbols (as aliases), rather than entire namespaces.
481 // Reserved for language binding use.
482 Releasable *lang_priv;
489 Symbol(const String *_name) : name(_name)
499 NameSpace *get_ns() const
504 const String *get_name() const
509 // If append is non-NULL, it is appended to non-user namespaces,
510 // to facilitate a language binding that cannot place nested types
511 // in the same language construct as the actual interface. The
512 // recommended suffix is "_ns", which is a reserved ending in the
513 // IDL. No suffix is placed on the final component of the name,
514 // even if it is a non-user namespace. The not_last field is used
515 // to detect whether it is the final component; it is only used
516 // internally, and should always be false when called externally.
518 // This function does *NOT* add a null first element to indicate
519 // that the name is fully qualified. If you need that, you have
520 // to add it yourself (call 'push_front(new String(""))' on the
523 StrList *get_fq_name(const char *append = NULL,
524 bool not_last = false) const;
526 virtual void lookup_imports()
530 virtual void lookup_chain()
534 virtual void lookup_misc()
538 virtual void final_analysis()
542 // These two methods must be implemented by all IDL symbols, but are
543 // not needed in CDL symbols (and therefore are not pure virtual).
545 virtual void output(const char *root)
549 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL)
553 // Find and return the topmost symbol other than a user namespace
554 // containing this symbol. If this symbol's parent is a user
555 // namespace, it returns itself. May not be called on the
556 // toplevel namespace.
558 Symbol *find_toplevel_type();
560 // Get the true type of the symbol, regardless of whether it is an
563 virtual Symbol *get_concrete_sym(bool follow_typedefs = true)
568 friend class NameSpace;
571 typedef Ref<Symbol> SymbolRef;
573 class SymList : public list<SymbolRef>, public RefCountable<SymList> {};
574 typedef Ref<SymList> SymListRef;
576 struct SymbolNotFound {
579 struct DuplicateSymbol {
582 struct InvalidArgument {
588 typedef Ref<NameSpace> NameSpaceRef;
590 class NameSpace : public virtual Symbol {
592 // Filesystem path to the external symbol storage, or NULL
593 // if not an import namespace.
595 // Import namespaces are read-only namespaces which are created
596 // for the importation of externally-declared symbols. One is
597 // initially created for each "mount point" specified by the user;
598 // whenever such a namespace is searched, it checks the external
599 // storage, and if the lookup succeeds, the symbol is loaded and
600 // added to the namespace. Failed lookups could be cached with a
601 // special BadSymbol or some such, as the imported namespace is
602 // assumed to be constant, but I don't think such an optimization
603 // is worthwhile, at least at this point.
607 // Load a symbol from external storage, constructing the relevant type
608 // of object, and adding it to this namespace. Only called for
609 // import namespaces.
611 Symbol *load(const String *symname);
613 typedef map<StringRef, SymbolRef> tbl_type;
616 list<StrListRef> import_strs;
617 list<NameSpaceRef> imports;
620 // This is set in the destructor, so the contents of the namespace
621 // don't try to remove themselves from the namespace when destructed
622 // due to the destruction of map.
625 // This is a counter for generating unique names for anonymous
626 // members of the namespace.
629 NameSpace() : dying(0), anon(0)
638 // Return a description of the type of namespace, for
640 virtual const char *description()
645 virtual void output(const char *root);
647 typedef tbl_type::const_iterator const_iterator;
648 typedef tbl_type::value_type value_type;
650 // Derived classes can throw InvalidArgument if you give them
651 // a type of Symbol that they don't accept; see their comments
652 // for more details. Unfortunately, this cannot be done
653 // with static type-checking, as there are places that know
654 // they've been given a namespace that can accept a particular
655 // type of symbol, but they don't know exactly what kind of
656 // namespace it is. C++'s type system is not sufficient to
657 // express this (at least not while retaining any semblance
660 // DuplicateSymbol is thrown if sym already exists in this namespace.
661 virtual void add(Symbol *sym, bool from_import)
663 if (path && !from_import)
664 throw InvalidArgument();
667 sym->external = true;
672 pair<const_iterator, bool> ret = tbl.insert(value_type(sym->name, sym));
677 throw DuplicateSymbol();
681 // Add the symbol to this namespace, handling duplicate symbols by
682 // printing an error and throwing a UserError(). This should not be
683 // done in the symbol's constructor, as the parent may not accept
684 // the symbol until it is fully constructed (the RTTI information
685 // changes, and in general partially constructed objects shouldn't
686 // be exposed to the rest of the system).
688 void add_user(Symbol *sym);
690 // Like add_user, but used by the import code. Duplicate
691 // symbols result in internal errors, and the add is done with
692 // from_import set to true. InvalidArgument results in an error
693 // message and a reraise as UserError.
695 // All conditions checked by the parent namespace's add() method
696 // (such as constness of data) must be satisfied prior to calling
697 // add_import(). On the other hand, add_import() must be called
698 // before any recursive importation is done which could
699 // conceivably try to import the current symbol (thus causing
700 // infinite recursion).
702 void add_import(Symbol *sym, const char *filename);
704 // SymbolNotFound is thrown if sym is not in this namespace.
705 virtual void del(Symbol *sym)
707 fprintf(stderr, "Removing symbol %s\n",
708 sym->get_fq_name()->flatten()->c_str());
710 if (tbl.erase(sym->name) == 0)
711 throw SymbolNotFound();
717 Symbol *lookup_noex_noimport(const String *symname)
719 const_iterator ret = tbl.find(symname);
721 if (ret != tbl.end())
722 return (*ret).second;
728 Symbol *lookup_noex(const String *symname, bool priv_ok = false)
730 Symbol *ret = NameSpace::lookup_noex_noimport(symname);
735 if (ret && !priv_ok && ret->priv)
741 Symbol *lookup(const String *symname, bool priv_ok = false)
743 Symbol *ret = lookup_noex(symname, priv_ok);
746 throw SymbolNotFound();
751 // Like lookup_noex, but also checks imported namespaces,
752 // and returns the namespace containing the match rather
753 // than the match itself.
755 NameSpace *search(const String *name, Symbol *exclude);
757 void add_search(StrList *ns)
759 import_strs.push_back(ns);
762 // Return a string containing case information manglement.
763 // See input.cc for more information.
765 static const String *mangle(const String *name);
767 const String *get_path()
772 // Import all members of this namespace. A no-op if not an import
776 // As import_all, but also recursively applies to any sub-namespaces.
777 void import_all_recursive();
779 const_iterator begin()
789 virtual void lookup_imports();
791 virtual void lookup_chain()
793 for (const_iterator i = begin(); i != end(); ++i) {
794 Symbol *sym = (*i).second;
799 virtual void lookup_misc()
801 for (const_iterator i = begin(); i != end(); ++i) {
802 Symbol *sym = (*i).second;
807 virtual void final_analysis()
809 for (const_iterator i = begin(); i != end(); ++i) {
810 Symbol *sym = (*i).second;
811 sym->final_analysis();
817 extern NameSpaceRef cur_nspace;
818 extern list<NameSpaceRef> nspace_stack;
820 typedef std::vector<StringRef> StringVec;
822 string *stringvec_to_path(StringVec &stringvec, const char *prepend);
824 // lookup_sym and lookup_type throw UserError on user error
825 // The context namespace is required for the proper
826 // set of namespaces to be searched.
828 Symbol *lookup_sym(NameSpace *topns, StrList *name, NameSpace *ctx,
829 Symbol *exclude = NULL);
832 const char *self; // Pointer to the type-specific struct
833 int self_len; // Length of the type-specific struct
836 CompiledDefHeader hdr;
838 // sym is the symbol from which to get the path/name, and
839 // dir is true if it should be "name/.self" rather than
841 void output_self(const char *dir, Symbol *sym, bool dir);
844 Def(const char *self, int self_len, CompiledDefHeader::Type type) :
845 self(self), self_len(self_len)
847 hdr.magic = CompiledDefHeader::magic_normal;
855 // Specific types may override this to output extra data
856 // to the .self file without having to reopen the file.
858 // Returns false on error.
860 virtual bool output_extra(FILE *f)
866 // Internal context struct used by input.cc to avoid passing
867 // lots of parameters around
868 struct ImportContext;
870 // This represents an actual IDL namespace {}, rather than
871 // a derived namespace such as a Struct or Interface.
873 class UserNameSpace : public NameSpace, public Def {
875 CompiledNameSpace def;
876 StringRef mountpoint_name;
878 UserNameSpace(const String *name = NULL) :
880 Def((const char *)&def, sizeof(def), CompiledDefHeader::NameSpace)
882 mountpoint_name = get_fq_name()->flatten();
883 def.length = mountpoint_name->length();
886 virtual void output(const char *root);
887 bool output_extra(FILE *f);
889 static void declare_import(const char *path);
891 static UserNameSpace *import(ImportContext &ctx);
892 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
895 typedef Ref<UserNameSpace> UserNameSpaceRef;
896 extern UserNameSpaceRef toplevel, cdl_toplevel;
897 extern UserNameSpace *output_ns;
899 class Type : public virtual Symbol {
909 virtual int get_default_bf_size()
911 // Only allow types in bitfields that explicitly
918 typedef Ref<Type> TypeRef;
920 // ctx can be NULL if basic_types_only is true
921 Type *lookup_type(StrList *sl, NameSpace *ctx, bool basic_types_only = false);
923 class BasicType : public Type, public Def {
925 CompiledBasicType def;
928 BasicType(const String *name) :
930 Def((const char *)&def, sizeof(def), CompiledDefHeader::BasicType)
933 memset(&def, 0, sizeof(def));
936 void init(CompiledBasicType &DEF)
944 static BasicType *declare(const String *name, NameSpace *parent,
945 CompiledBasicType &DEF)
947 BasicType *bt = new BasicType(name);
951 parent->add_user(bt);
956 virtual void output(const char *root);
958 static BasicType *import(ImportContext &ctx);
959 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
962 static inline bool is_array(CompiledBasicType &bt)
964 return bt.array.bounds[0] || bt.array.bounds[1];
967 static inline bool is_array(CompiledBasicType *bt)
969 return is_array(*bt);
972 typedef Ref<Datum> DatumRef;
974 class Array : public RefCountable<Array>
976 NameSpace *lookup_ctx;
979 // lower is [0], upper is [1]
983 // Strings for error reporting on each constant. If the constant
984 // is symbolic, then this is the fully qualified symbol name.
985 // Otherwise, it is the numerical value converted to a string. In
986 // each case, the file/line shall correspond to where the array
987 // bound was specified.
992 // ca is not valid until after final_analysis() is called.
995 Array(NameSpace *LOOKUP_CTX);
996 void set_bound(Con &con, int bound);
997 void final_analysis();
999 void set_unbounded();
1002 typedef Ref<Array> ArrayRef;
1004 class Datum : public Symbol, public Def {
1005 StrListRef type_name;
1007 StringRef type_fq_name;
1009 StrListRef const_val_name;
1010 SymbolRef const_val_sym;
1013 bool basic; // Datum is of a BasicType
1015 bool const_init; // Datum's constant has been initialized; this is
1016 // true after a successful verify_const().
1017 CompiledBasicType *cbt;
1021 int chain_traversed;
1023 // Recursively retrieve the actual value of a const datum
1024 // initialized with another named const datum. Returns
1025 // the "end" of an infinite loop, if one is found. Once
1026 // the full infinite loop has been printed, UserError is
1029 Datum *resolve_constant_chain();
1031 void init_const_early(Con *con);
1033 void use_anon_type(const CompiledBasicType &CBT)
1035 def.basictype = CBT;
1036 cbt = &def.basictype;
1039 def.type.length = 0;
1042 void process_type();
1044 void set_array(Array *ARRAY)
1054 int con_type; // Used to store the TOK_[IUF]CON of the Con struct
1055 // for type checking once the type is known.
1057 Datum(const String *name) :
1059 Def((const char *)&def, sizeof(def), CompiledDefHeader::Datum)
1063 chain_traversed = 0;
1064 memset(&def, 0, sizeof(def));
1067 void init(StrList *type, Array *ARRAY, Con *con = NULL);
1068 void init(CompiledBasicType &cbt, Array *ARRAY, Con *con = NULL);
1070 static Datum *declare(const String *name, NameSpace *parent,
1071 StrList *type, Array *ARRAY,
1076 Datum *d = new Datum(name);
1077 d->init(type, ARRAY, con);
1079 parent->add_user(d);
1083 static Datum *declare(const String *name, NameSpace *parent,
1084 CompiledBasicType &type,
1085 Array *ARRAY, Con *con = NULL)
1089 Datum *d = new Datum(name);
1090 d->init(type, ARRAY, con);
1092 parent->add_user(d);
1098 def.flags.field.Inline = 1;
1103 return def.flags.field.Inline;
1106 void set_immutable()
1108 def.flags.field.Immutable = 1;
1113 return def.flags.field.Immutable;
1116 // Returns true if the constant was acceptable, false otherwise (an
1117 // error is also output to the user in this case).
1119 bool verify_const();
1121 virtual void lookup_chain()
1126 const_val_sym = lookup_sym(toplevel, const_val_name, get_ns());
1130 type_sym = lookup_type(type_name, get_ns(), true);
1132 type_sym = lookup_sym(toplevel, type_name, get_ns());
1138 virtual void lookup_misc()
1140 if (def.flags.field.Const) {
1142 assert(def.flags.field.Const);
1145 Datum *d = resolve_constant_chain();
1155 virtual void final_analysis();
1157 virtual void output(const char *root);
1158 bool output_extra(FILE *f);
1160 static Datum *import(ImportContext &ctx);
1161 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1163 uint64_t get_ucon(const String *err_str)
1165 if (!def.flags.field.Const) {
1166 yyerrorfl(err_str->file, err_str->line,
1167 "\"%s\" is not a const Datum.\n",
1168 get_fq_name()->flatten()->c_str());
1178 return ::is_array(def.basictype);
1182 template<typename T>
1183 bool output_list(T *sym, FILE *f);
1185 class BitField : public NameSpace, public Type, public Def {
1186 list<DatumRef> entries;
1188 void add_elem(Datum *d);
1191 CompiledBitField def;
1194 BitField(const String *name) :
1196 Def((const char *)&def, sizeof(def), CompiledDefHeader::BitField)
1198 memset(&def, 0, sizeof(def));
1201 void init(int bits, NameSpace *parent)
1203 if (bits < 0 || bits > 64) {
1204 yyerrorf("\"%s\" has invalid bitfield size %d",
1205 name->c_str(), bits);
1207 bits = bits < 0 ? 0 : 64;
1213 static BitField *declare(const String *name, NameSpace *parent,
1218 BitField *bf = new BitField(name);
1219 bf->init(bits, parent);
1221 parent->add_user(bf);
1225 // Only integral Datums, Enums, and BitFields can be added.
1227 void add(Symbol *sym, bool from_import);
1229 virtual const char *description()
1234 virtual void lookup_misc()
1236 NameSpace::lookup_misc();
1239 virtual void final_analysis()
1241 // FIXME: check total size of elements
1243 NameSpace::final_analysis();
1246 int get_default_bf_size()
1251 virtual void output(const char *root);
1252 bool output_extra(FILE *f);
1254 static BitField *import(ImportContext &ctx);
1255 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1257 typedef list<DatumRef>::const_iterator entries_iterator;
1258 typedef list<DatumRef>::const_reverse_iterator entries_reverse_iterator;
1260 entries_iterator entries_begin()
1262 return entries.begin();
1265 entries_iterator entries_end()
1267 return entries.end();
1270 entries_reverse_iterator entries_rbegin()
1272 return entries.rbegin();
1275 entries_reverse_iterator entries_rend()
1277 return entries.rend();
1282 typedef Ref<Struct> StructRef;
1283 extern Struct *System_VStruct;
1285 // FIXME: typedefed superstructs
1286 class Struct : public NameSpace, public Type, public Def {
1287 list<DatumRef> entries;
1290 StrListRef supername;
1291 bool attrs_resolved;
1293 // 0 = unknown, 1 = yes, 2 = no
1296 void add_elem(Datum *d);
1298 void resolve_attrs()
1303 if (super && !super->attrs_resolved)
1304 super->resolve_attrs();
1306 if (super && super->def.flags.field.Virtual)
1307 def.flags.field.Virtual = 1;
1309 attrs_resolved = true;
1315 // This is not maintained by the generic code, but can be
1316 // used by language bindings to cache the result of the
1321 Struct(const String *name) :
1323 Def((const char *)&def, sizeof(def), CompiledDefHeader::Struct)
1325 memset(&def, 0, sizeof(def));
1329 void init(StrList *SUPERNAME)
1331 supername = SUPERNAME;
1334 static Struct *declare(const String *name, NameSpace *parent,
1339 Struct *st = new Struct(name);
1340 st->init(SUPERNAME);
1342 parent->add_user(st);
1348 def.flags.field.Virtual = 1;
1353 def.flags.field.Inline = 1;
1358 return def.flags.field.Virtual;
1363 return def.flags.field.Inline;
1366 // Only Datums and Types can be added.
1368 void add(Symbol *sym, bool from_import);
1370 virtual const char *description()
1377 assert(current_pass >= 4);
1381 virtual void lookup_chain()
1384 supersym = lookup_sym(toplevel, supername, get_ns());
1388 NameSpace::lookup_chain();
1394 if (supersym && !super) {
1395 super = dynamic_cast<Struct *>(supersym->get_concrete_sym());
1398 const String *str = supername->back();
1399 yyerrorfl(str->file, str->line,
1400 "\"%s\" is not a struct.",
1401 supersym->get_fq_name()->flatten()->c_str());
1404 def.flags.field.Super = 1;
1405 super->lookup_super();
1407 if (super->is_virtual())
1411 if (is_virtual() && !supersym && !super) {
1412 assert(System_VStruct);
1413 if (this != System_VStruct) {
1414 def.flags.field.Super = 1;
1415 super = System_VStruct;
1421 virtual void lookup_misc()
1425 if (is_virtual() && def.guid[0] == 0 && def.guid[1] == 0)
1426 yyerrorfl(name->file, name->line,
1427 "Virtual struct \"%s\" is missing a GUID.",
1428 get_fq_name()->flatten()->c_str());
1430 NameSpace::lookup_misc();
1433 virtual void final_analysis()
1435 // FIXME: check for infinite loops in struct inheritance
1438 NameSpace::final_analysis();
1441 virtual void output(const char *root);
1442 bool output_extra(FILE *f);
1444 static Struct *import(ImportContext &ctx);
1445 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1447 typedef list<DatumRef>::const_iterator entries_iterator;
1449 entries_iterator entries_begin()
1451 return entries.begin();
1454 entries_iterator entries_end()
1456 return entries.end();
1459 void set_guid(uint64_t guid[2])
1461 if (def.guid[0] || def.guid[1])
1462 yyerrorf("\"%s\" already has a GUID.",
1463 get_fq_name()->flatten()->c_str());
1465 def.guid[0] = guid[0];
1466 def.guid[1] = guid[1];
1469 // A struct is "plain data" if it contains no object references,
1470 // no non-inline arrays or structs, and no inline non-plain structs.
1471 bool is_plain_data();
1474 class Param : public Symbol, public Def {
1475 StrListRef type_name;
1476 StringRef type_fq_name;
1478 bool basic; // Datum is of a BasicType
1483 void use_named_type(BasicType *bt)
1485 assert(!bt || bt->def.flags.field.TypeDef);
1489 type_fq_name = type->get_fq_name()->flatten();
1490 def.type.length = type_fq_name->length();
1493 void use_anon_type(const CompiledBasicType &cbt)
1495 def.basictype = cbt;
1500 void set_array(Array *ARRAY)
1510 Param(const String *name) :
1512 Def((const char *)&def, sizeof(def), CompiledDefHeader::Param)
1514 memset(&def, 0, sizeof(def));
1517 void init(StrList *TYPE, CompiledParam::Flags flags, Array *ARRAY)
1524 static Param *declare(const String *name, NameSpace *parent,
1525 StrList *TYPE, CompiledParam::Flags flags,
1528 virtual void lookup_misc()
1530 type = lookup_type(type_name, get_ns());
1533 virtual void final_analysis()
1535 BasicType *bt = dynamic_cast<BasicType *>(type->get_concrete_sym());
1537 if (bt && !bt->def.flags.field.TypeDef) {
1538 use_anon_type(bt->def);
1542 Struct *str = dynamic_cast<Struct *>(*type);
1543 if (str && str->is_inline())
1546 if (!str && is_inline()) {
1547 yyerrorfl(name->file, name->line,
1548 "\"%s\" is static but not a struct.",
1549 get_fq_name()->flatten()->c_str());
1554 array->final_analysis();
1555 def.basictype.array = array->ca;
1557 def.basictype.array.bounds[0] = 0;
1558 def.basictype.array.bounds[1] = 0;
1564 def.flags.field.Inline = 1;
1569 return def.flags.field.Inline;
1574 return def.flags.field.In;
1579 return def.flags.field.Out;
1582 virtual void output(const char *root);
1583 bool output_extra(FILE *f);
1585 static Param *import(ImportContext &ctx);
1586 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1590 return ::is_array(def.basictype);
1594 typedef Ref<Param> ParamRef;
1596 class Method : public NameSpace, public Def {
1597 list<ParamRef> entries;
1599 void add_elem(Param *p);
1604 Method(const String *name) :
1606 Def((const char *)&def, sizeof(def), CompiledDefHeader::Method)
1608 memset(&def, 0, sizeof(def));
1613 def.flags.field.Async = 1;
1618 return def.flags.field.Async;
1621 static Method *declare(const String *name, NameSpace *parent);
1623 void add(Symbol *sym, bool from_import);
1625 virtual const char *description()
1630 virtual void output(const char *root);
1631 bool output_extra(FILE *f);
1633 static Method *import(ImportContext &ctx);
1634 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1636 typedef list<ParamRef>::const_iterator entries_iterator;
1638 entries_iterator entries_begin()
1640 return entries.begin();
1643 entries_iterator entries_end()
1645 return entries.end();
1649 typedef Ref<Method> MethodRef;
1652 typedef Ref<Interface> InterfaceRef;
1654 extern Interface *System_Object;
1656 // FIXME: typedefed superinterfaces
1657 class Interface : public NameSpace, public Type, public Def {
1658 list<MethodRef> methods;
1659 list<InterfaceRef> supers;
1660 IDListRef supernames;
1662 void add_elem(Method *m);
1664 // This is like Symbol::traversed[], but used internally by the
1665 // for_each_super function to ensure that common ancestors are only
1668 int traversed_all_supers;
1669 static int all_supers_traversal;
1672 typedef void (*callback)(Interface *i, void *arg);
1675 template<callback cb>
1676 void for_each_super_internal(void *arg)
1678 for (supers_iterator i = supers_begin(); i != supers_end(); ++i) {
1679 Interface *iface = *i;
1681 if (iface->traversed_all_supers < all_supers_traversal) {
1682 iface->traversed_all_supers = all_supers_traversal;
1684 iface->for_each_super_internal<cb>(arg);
1689 // All interfaces in the map and vector are supers of this
1690 // interface, and thus retained that way, so plain pointers
1691 // can be used here.
1693 typedef map<Interface *, int> chain_map_type;
1694 typedef chain_map_type::value_type chain_valtype;
1695 typedef chain_map_type::const_iterator chain_iter;
1697 chain_map_type super_to_chain_map;
1701 vector<Interface *> chain_heads;
1704 int super_to_chain(Interface *iface, bool must_find_it = true)
1706 chain_iter ret = super_to_chain_map.find(iface);
1708 if (ret == super_to_chain_map.end()) {
1709 assert(!must_find_it);
1713 return (*ret).second;
1716 Interface *get_chain_head(int chain)
1718 return chain_heads[chain];
1721 int get_num_chains()
1727 void set_chain(Interface *iface, int chain)
1729 pair<chain_iter, bool> ret =
1730 super_to_chain_map.insert(chain_valtype(iface, chain));
1734 // This is the inner depth-first search, which terminates
1735 // at each level upon finding that the node it had previously
1736 // recursed into found an unchained node.
1738 void pick_chain(Interface *iface, int chain)
1740 assert(super_to_chain(iface, false) == -1);
1741 chain_heads.push_back(iface);
1744 set_chain(iface, chain);
1746 if (iface->supers.empty())
1749 iface = iface->supers.front();
1750 } while (super_to_chain(iface, false) == -1);
1753 // This is the outer breadth-first-search, making sure every
1754 // super is assigned to a chain.
1758 list<Interface *> bfs;
1761 bfs.push_back(this);
1763 while (!bfs.empty()) {
1764 Interface *iface = bfs.front();
1767 for (supers_iterator i = iface->supers_begin();
1768 i != iface->supers_end(); ++i)
1771 if (super_to_chain(iface, false) == -1)
1772 pick_chain(iface, num_chains++);
1777 // Do not call after lookup_misc
1778 void add_super(Interface *i)
1780 assert(current_pass != 1);
1782 supers.push_back(i);
1786 CompiledInterface def;
1788 Interface(const String *name) :
1790 Def((const char *)&def, sizeof(def), CompiledDefHeader::Interface)
1792 memset(&def, 0, sizeof(def));
1793 traversed_all_supers = 0;
1796 void init(IDList *SUPERNAMES)
1798 supernames = SUPERNAMES;
1801 static Interface *declare(const String *name, NameSpace *parent,
1806 Interface *i = new Interface(name);
1807 i->init(SUPERNAMES);
1809 parent->add_user(i);
1813 // Only Methods, Types, and const BasicType Datums can be added.
1815 void add(Symbol *sym, bool from_import);
1817 virtual const char *description()
1823 void add_object_super()
1825 assert(System_Object);
1826 if (this != System_Object && supers.empty())
1827 add_super(System_Object);
1831 virtual void lookup_misc()
1833 if (def.guid[0] == 0 && def.guid[1] == 0)
1834 yyerrorfl(name->file, name->line,
1835 "Interface \"%s\" is missing a GUID.",
1836 get_fq_name()->flatten()->c_str());
1839 for (IDList::iterator i = supernames->begin();
1840 i != supernames->end(); ++i)
1842 Symbol *sym = lookup_sym(toplevel, *i, get_ns());
1844 dynamic_cast<Interface *>(sym->get_concrete_sym());
1847 const String *str = (*i)->back();
1848 yyerrorfl(str->file, str->line,
1849 "\"%s\" is not an interface.\n",
1850 sym->get_fq_name()->flatten()->c_str());
1860 NameSpace::lookup_misc();
1863 virtual void final_analysis()
1865 // FIXME: check for infinite loops in inheritance
1868 NameSpace::final_analysis();
1871 virtual void output(const char *root);
1872 bool output_extra(FILE *f);
1874 static Interface *import(ImportContext &ctx);
1875 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1877 typedef list<MethodRef>::const_iterator methods_iterator;
1878 typedef list<InterfaceRef>::const_iterator supers_iterator;
1880 supers_iterator supers_begin()
1882 assert(current_pass != 1);
1883 return supers.begin();
1886 supers_iterator supers_end()
1888 return supers.end();
1893 assert(current_pass != 1);
1894 return supers.empty();
1897 methods_iterator methods_begin()
1899 return methods.begin();
1902 methods_iterator methods_end()
1904 return methods.end();
1907 template<callback cb>
1908 void for_each_super(void *arg)
1910 assert(current_pass >= 4);
1912 all_supers_traversal++;
1913 for_each_super_internal<cb>(arg);
1916 void finalize_class_iface()
1922 void set_guid(uint64_t guid[2])
1924 if (def.guid[0] || def.guid[1])
1925 yyerrorf("\"%s\" already has a GUID.",
1926 get_fq_name()->flatten()->c_str());
1928 def.guid[0] = guid[0];
1929 def.guid[1] = guid[1];
1933 class IFaceList : public list<InterfaceRef>,
1934 public RefCountable<IFaceList> {};
1936 class Enum : public NameSpace, public Type, public Def {
1937 list<DatumRef> entries;
1939 void add_elem(Datum *d);
1942 unsigned int next_val;
1945 Enum(const String *name) :
1947 Def((const char *)&def, sizeof(def), CompiledDefHeader::Enum),
1950 memset(&def, 0, sizeof(def));
1955 if (bits < 0 || bits > 64) {
1956 yyerrorf("\"%s\" has invalid enum size %d",
1957 name->c_str(), bits);
1959 bits = bits < 0 ? 0 : 64;
1965 static Enum *declare(const String *name, NameSpace *parent,
1970 Enum *e = new Enum(name);
1973 parent->add_user(e);
1977 // Only const unsigned integer BasicType Datums are allowed.
1979 void add(Symbol *sym, bool from_import);
1981 virtual const char *description()
1983 return "enumeration";
1986 int get_default_bf_size()
1991 virtual void output(const char *root);
1992 bool output_extra(FILE *f);
1994 static Enum *import(ImportContext &ctx);
1995 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
1997 typedef list<DatumRef>::const_iterator entries_iterator;
1999 entries_iterator entries_begin()
2001 return entries.begin();
2004 entries_iterator entries_end()
2006 return entries.end();
2010 class Alias : public Symbol, public Def {
2016 Cycle(Alias *END) : end(END)
2025 StringRef sym_fq_name;
2026 StrListRef sym_name;
2028 Alias(const String *name) :
2030 Def((const char *)&def, sizeof(def), CompiledDefHeader::Alias)
2032 memset(&def, 0, sizeof(def));
2033 lookup_begun = false;
2036 void init(StrList *symname, bool is_private)
2042 static Alias *declare(const String *name, NameSpace *parent,
2043 StrList *symname, bool is_private = false)
2046 Alias *a = new Alias(name);
2047 a->init(symname, is_private);
2049 parent->add_user(a);
2053 void resolve_chain()
2057 yyerrorfl(name->file, name->line,
2058 "Alias loop defining \"%s\"",
2059 get_fq_name()->flatten()->c_str());
2064 lookup_begun = true;
2067 real_sym = lookup_sym(toplevel, sym_name, get_ns(), this);
2071 yyerrorfl(name->file, name->line, " ...referenced by \"%s\"",
2072 get_fq_name()->flatten()->c_str());
2082 virtual Symbol *get_concrete_sym(bool follow_typedefs = true)
2085 return real_sym->get_concrete_sym(follow_typedefs);
2088 virtual void lookup_chain()
2090 get_concrete_sym(true);
2093 virtual void lookup_misc()
2095 real_sym = real_sym->get_concrete_sym(false);
2096 sym_fq_name = real_sym->get_fq_name()->flatten();
2098 def.length = sym_fq_name->length();
2101 virtual void output(const char *root);
2102 bool output_extra(FILE *f);
2104 static Alias *import(ImportContext &ctx);
2105 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
2108 class TypeDef : public Alias {
2110 TypeDef(const String *name) : Alias(name)
2112 memset(&def, 0, sizeof(def));
2113 hdr.type = CompiledDefHeader::TypeDef;
2116 static TypeDef *declare(const String *name, NameSpace *parent,
2120 TypeDef *td = new TypeDef(name);
2121 td->init(symname, false);
2123 parent->add_user(td);
2127 virtual Symbol *get_concrete_sym(bool follow_typedefs = true)
2129 if (follow_typedefs) {
2131 return real_sym->get_concrete_sym(follow_typedefs);
2137 static TypeDef *import(ImportContext &ctx);
2138 virtual void output_lang(LangCallback *lcb, int arg = 0, void *arg2 = NULL);
2141 NameSpace *add_nspace(StrList *name, bool push);
2144 // Declare an instance of "type" in "ns" for each element of "ids".
2145 // This function will report any errors, but not throw UserError.
2147 void declare_data(NameSpace *ns, StrList *ids, StrList *type,
2148 Array *array, StrList *attr);
2149 void declare_aliases(NameSpace *ns, StrList *ids, StrList *type,
2151 void declare_basictypes(NameSpace *ns, StrList *ids,
2152 BasicType *type, bool is_typedef);
2154 // You'd think they'd have standard functions to do this these days.
2155 // All I could find that come close are the network-byte-order
2156 // functions, and they're no-ops on big-endian machines.
2158 static inline uint32_t swap32(uint32_t in, bool swap)
2161 return ((in & 0x000000ff) << 24) |
2162 ((in & 0x0000ff00) << 8) |
2163 ((in & 0x00ff0000) >> 8) |
2164 ((in & 0xff000000) >> 24);
2169 static inline uint64_t swap64(uint64_t in, bool swap)
2172 return (((uint64_t)swap32((uint32_t)in, true)) << 32) |
2173 swap32((uint32_t)(in >> 32), true);
2191 File *operator =(FILE *F)
2209 // Verify that a prospective new import (or output namespace)
2210 // does not overlap an existing import. Returns the conflicting
2211 // import, or NULL if none found.
2213 NameSpace *check_for_imports(NameSpace *ns);