Developer appendix · free

IFC for developers

The grammar under the file, the schema behind it, and what it takes to parse big files, write valid ones and check them. With the open-source libraries side by side.

25 min reading

The chapters teach IFC through the file. This page is for the moment you write code against it: a parser, an exporter, a checker or a pipeline. It assumes you’ve read chapter 1 and know what a STEP instance looks like.

The concepts are tool-neutral. The code uses two open-source libraries, side by side: IFClite (JavaScript) and IfcOpenShell (Python). Every snippet on this page and in the chapters runs in the course’s test suite against the course models, with pinned versions, and the tests check that both libraries find the same answers.

The grammar: ISO 10303-21

An .ifc file is a STEP physical file, also called “SPF” or “Part 21”, after ISO 10303-21. IFC 4.3 cites ISO 10303-21 without a date; IFC files are written in the second-edition (2002) syntax and declare implementation level 2;1. The current edition is the third, ISO 10303-21:2016; more on that below.

A file has four parts, always in this order: the start line ISO-10303-21;, a HEADER section, a DATA section and the end line END-ISO-10303-21;. The header holds three entities:

Every instance in DATA is one statement, #id=ENTITY(attribute, attribute, …);. Attribute values are one of:

Token Meaning
$ not set (an OPTIONAL attribute left empty)
* derived: the schema computes it, the file doesn’t store it
#43 a reference to another instance
'text' a string
12, -0.15, 1.E-05 an integer or a real (a real always has a .)
.T., .F., .U., .ELEMENT. a boolean, a logical, an enumeration value
(…, …) a list, set or bag
IFCLABEL('EI60') a typed value, needed where a SELECT allows several types

Instance ids are only labels: they have to be unique in the file and nothing else. They don’t need to be in order, and a reference may point forward. A writer can renumber freely, as chapter 1 shows.

Strings and their escapes

A string is enclosed in '. Inside it, a ' is doubled ('') and a \ is doubled (\\). Everything else outside printable ASCII needs a control directive:

A comment is /* … */ and can’t be nested. Whitespace between tokens doesn’t matter.

The classic tokenizer bug is to split on ; or to strip comments before you’ve found the strings. ;, /* and #12 inside quotes are text. Here is a hand-written file that tries all of it:

ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('ViewDefinition [ReferenceView]'),'2;1');
FILE_NAME('part21.ifc','2026-11-08T10:00:00',('How IFC Works'),('LTplus AG'),'','hand-written','');
FILE_SCHEMA(('IFC4X3_ADD2'));
ENDSEC;
DATA;
/* A comment can sit between instances. Inside quotes, ; and /* are just text. */
#1=IFCPROJECT('0YvctVUKr0kugbFTf53O9L',$,'Part 21 demo',$,$,$,$,$,$);
#2=IFCWALL('2O2Fr$t4X7Zf8NOew3FLOH',$,'T\X2\00FC\X0\r; Gel\S\dnder','It''s /* not */ a comment',$,$,$,$,$);
ENDSEC;
END-ISO-10303-21;
Do it in code: read the escaped strings

IFClite (JavaScript)

Save part21.ifc next to the script, run npm install @ifc-lite/parser@9.9.0, then node part21.mjs. IFClite also notes on stderr that the file has no units and no storeys; for a file this small that’s expected.

// Read the escapes of ISO 10303-21 strings: \X2\…\X0\, \S\ and the doubled ''. (For developers)
// npm install @ifc-lite/parser@9.9.0, save part21.ifc next to this file, run: node part21.mjs
import { readFile } from 'node:fs/promises';
import { IfcParser, getAttributeNamesForSchema } from '@ifc-lite/parser';

const store = await new IfcParser().parseColumnar(new Uint8Array(await readFile('part21.ifc')).buffer);
const { type, attributes } = store.getEntity(2);
const names = getAttributeNamesForSchema(type, store.schemaVersion);
console.log(`${names[2]}: ${attributes[2]}`); // 'T\X2\00FC\X0\r; Gel\S\dnder' in the file
console.log(`${names[3]}: ${attributes[3]}`); // 'It''s /* not */ a comment' in the file

IfcOpenShell (Python)

Save part21.ifc next to the script, run pip install ifcopenshell==0.8.5, then python part21.py. IfcOpenShell decodes strings when you read an attribute and encodes them when you write one.

# Read the escapes of ISO 10303-21 strings: \X2\…\X0\, \S\ and the doubled ''. (For developers)
# pip install ifcopenshell==0.8.5, save part21.ifc next to this file, run: python part21.py
import ifcopenshell

wall = ifcopenshell.open('part21.ifc').by_id(2)
print(f'Name: {wall.Name}')  # 'T\X2\00FC\X0\r; Gel\S\dnder' in the file
print(f'Description: {wall.Description}')  # 'It''s /* not */ a comment' in the file

Both print:

Name: Tür; Geländer
Description: It's /* not */ a comment

What the third edition added

ISO 10303-21:2016 adds an ANCHOR section (names that other files can point at), a REFERENCE section (instances that live in another file), a SIGNATURE section, strings written directly in UTF-8, and ZIP archives of several files. The public final draft at STEP Tools is the readable version. Several DATA sections were already allowed in the second edition.

IFC uses none of this. An IFC file has one HEADER and one DATA section, and ifcZIP is a ZIP archive around one .ifc. If your parser meets ANCHOR;, the file isn’t IFC.

EXPRESS: where the attribute order comes from

The file stores values by position. Which position means what is defined in the schema, written in EXPRESS, ISO 10303-11. buildingSMART publishes the IFC 4.3 schema as one file, IFC4X3_ADD2.exp (there’s also a mirror on GitHub). Two entities from it, slightly shortened:

ENTITY IfcRoot
ABSTRACT SUPERTYPE OF (ONEOF (IfcObjectDefinition, IfcPropertyDefinition, IfcRelationship));
GlobalId : IfcGloballyUniqueId;
OwnerHistory : OPTIONAL IfcOwnerHistory;
Name : OPTIONAL IfcLabel;
Description : OPTIONAL IfcText;
UNIQUE
UR1 : GlobalId;
END_ENTITY;

ENTITY IfcWall
SUPERTYPE OF (ONEOF (IfcWallStandardCase))
SUBTYPE OF (IfcBuiltElement);
PredefinedType : OPTIONAL IfcWallTypeEnum;
WHERE
CorrectPredefinedType : NOT(EXISTS(PredefinedType)) OR
  (PredefinedType <> IfcWallTypeEnum.USERDEFINED) OR
  ((PredefinedType = IfcWallTypeEnum.USERDEFINED) AND EXISTS (SELF\IfcObject.ObjectType));
CorrectTypeAssigned : (SIZEOF(IsTypedBy) = 0) OR
  ('IFC4X3_ADD2.IFCWALLTYPE' IN TYPEOF(SELF\IfcObject.IsTypedBy[1].RelatingType));
END_ENTITY;

What you need to read it:

Both libraries generate their entity tables from these .exp files, so you rarely parse EXPRESS yourself. Chapter 5 shows how to ask the schema in code instead of from memory.

Parsing large files

A 13 MB file like the Clinic in chapter 1 has about 200,000 instances; models of 500 MB and more exist. Three strategies, in the order of how much they keep in memory:

Geometry is a separate cost. Turning a wall’s profile and extrusion into triangles, and cutting the openings, usually takes longer than parsing and produces more data than the file itself (see chapter 4). Do it lazily, per element, and off the main thread in a browser.

Do it in code: parse once, count what’s in the file

IFClite (JavaScript)

parseColumnar indexes the whole file and decodes attributes when you ask for them. Run npm install @ifc-lite/parser@9.9.0, then node count-types.mjs your.ifc. In a browser, run it in a Web Worker so the page stays responsive; parseColumnar also takes an onProgress callback.

// How big is a file, and what is it made of? Parse once, count instances per class. (For developers)
// npm install @ifc-lite/parser@9.9.0, then: node count-types.mjs your.ifc
import { readFile } from 'node:fs/promises';
import { IfcParser } from '@ifc-lite/parser';

const path = process.argv[2] ?? 'tiny-house.en.ifc';
const started = performance.now();
const bytes = await readFile(path);
// Columnar: one pass over the bytes builds typed-array columns and an index; instances are decoded on demand.
const store = await new IfcParser().parseColumnar(new Uint8Array(bytes).buffer);
const seconds = (performance.now() - started) / 1000;

const counts = [...store.entityIndex.byType].map(([type, ids]) => [type, ids.length]);
counts.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
console.log(`${path}: ${store.entityCount} instances, ${counts.length} classes`);
for (const [type, n] of counts.slice(0, 5)) console.log(`  ${type} ${n}`);
console.log(`parsed in ${seconds.toFixed(2)} s, ${Math.round(process.memoryUsage().rss / 2 ** 20)} MB resident`);

IfcOpenShell (Python)

ifcopenshell.open parses the file with IfcOpenShell’s C++ parser and gives you Python objects on demand. Run pip install ifcopenshell==0.8.5, then python count-types.py your.ifc. For very large files, ifcopenshell.open(path, should_stream=True) gives a pure-Python reader that indexes the file and parses an instance only when you ask for it.

# How big is a file, and what is it made of? Parse once, count instances per class. (For developers)
# pip install ifcopenshell==0.8.5, then: python count-types.py your.ifc
import resource
import sys
import time
from collections import Counter

import ifcopenshell

path = sys.argv[1] if len(sys.argv) > 1 else 'tiny-house.en.ifc'
started = time.perf_counter()
model = ifcopenshell.open(path)  # the C++ parser reads the whole file into memory
seconds = time.perf_counter() - started

counts = Counter(entity.is_a().upper() for entity in model)  # the file's spelling: IFCWALL
ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
print(f'{path}: {sum(counts.values())} instances, {len(counts)} classes')
for name, n in ranked[:5]:
    print(f'  {name} {n}')
peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // (2**20 if sys.platform == 'darwin' else 1024)  # bytes on macOS, kB elsewhere
print(f'parsed in {seconds:.2f} s, {peak} MB resident at most')

Both report the same instances and classes. On chapter 1’s model: 432 instances in 39 classes, most of them IFCCARTESIANPOINT (71).

What it costs, measured on 8 Nov 2026 with the scripts above on one laptop (Intel Core i9-13950HX, Linux, Node 24, Python 3.12), median of three runs:

File IFClite 9.9.0 IfcOpenShell 0.8.5
Chapter 1’s model, 21 KB, 432 instances 0.04 s, 118 MB under 0.01 s, 126 MB
Clinic, 13 MB, 209,259 instances 0.9 s, 245 MB 1.7 s, 275 MB

The memory column is the whole process: about 120 MB of it is the runtime and the library before the first byte is read. The parsed Clinic adds 130 to 150 MB, roughly ten times the file size. With should_stream=True, IfcOpenShell indexed the Clinic in 1.2 s and peaked at 211 MB. Treat these numbers as an order of magnitude, not a benchmark: they depend on the machine, the file and what else runs.

Writing IFC

Writing a file that opens is easy. Writing one that other tools read the way you meant takes a few rules:

Do it in code: write a wall with a FireRating

IFClite (JavaScript)

IfcCreator from @ifc-lite/create writes the project, the units, the contexts, site, building and the header for you; you add storeys, elements and property sets. Run npm install @ifc-lite/create@5.1.3, then node write-wall.mjs.

// Write a small, valid IFC4.3 file: project, site, building, storey and one wall with a FireRating. (For developers)
// npm install @ifc-lite/create@5.1.3, then: node write-wall.mjs   (writes wall.ifc)
import { writeFile } from 'node:fs/promises';
import { IfcCreator } from '@ifc-lite/create';

// The creator writes the spatial structure, units, the geometric context and the header for you.
// Every element gets a fresh GlobalId (22 characters, IFC's base-64 form of a 128-bit UUID).
const creator = new IfcCreator({ Name: 'Demo', Schema: 'IFC4X3', LengthUnit: 'METRE', Author: 'Your name', Organization: 'Your firm' });
const storey = creator.addIfcBuildingStorey({ Name: 'Ground floor', Elevation: 0 });
const wall = creator.addIfcWall(storey, { Name: 'W-01', Start: [0, 0, 0], End: [5, 0, 0], Thickness: 0.2, Height: 2.8 });
creator.addIfcPropertySet(wall, {
  Name: 'Pset_WallCommon',
  Properties: [{ Name: 'FireRating', NominalValue: 'EI60', Type: 'IfcLabel' }],
});

const { content } = creator.toIfc();
await writeFile('wall.ifc', content);
console.log(`wall.ifc: ${content.split('\n').filter((line) => line.startsWith('#')).length} instances`);

IfcOpenShell (Python)

ifcopenshell.api is IfcOpenShell’s editing layer, the one Bonsai (formerly BlenderBIM) is built on. Each call keeps the relationships right: aggregate.assign_object writes the IfcRelAggregates, spatial.assign_container the containment, pset.edit_pset the property values with the types the standard set expects. Run pip install ifcopenshell==0.8.5, then python write-wall.py.

# Write a small, valid IFC4.3 file: project, site, building, storey and one wall with a FireRating. (For developers)
# pip install ifcopenshell==0.8.5, then: python write-wall.py   (writes wall.ifc)
import ifcopenshell
import ifcopenshell.api.aggregate
import ifcopenshell.api.context
import ifcopenshell.api.geometry
import ifcopenshell.api.project
import ifcopenshell.api.pset
import ifcopenshell.api.root
import ifcopenshell.api.spatial
import ifcopenshell.api.unit

# ifcopenshell.api takes care of the bookkeeping: GlobalIds, relationships, the header.
model = ifcopenshell.api.project.create_file(version='IFC4X3')
project = ifcopenshell.api.root.create_entity(model, ifc_class='IfcProject', name='Demo')
ifcopenshell.api.unit.assign_unit(model, length={'is_metric': True, 'raw': 'METERS'})
context = ifcopenshell.api.context.add_context(model, context_type='Model')
body = ifcopenshell.api.context.add_context(
    model, context_type='Model', context_identifier='Body', target_view='MODEL_VIEW', parent=context)

# Spatial structure: project ⊃ site ⊃ building ⊃ storey, through IfcRelAggregates.
site = ifcopenshell.api.root.create_entity(model, ifc_class='IfcSite', name='Site')
building = ifcopenshell.api.root.create_entity(model, ifc_class='IfcBuilding', name='Building')
storey = ifcopenshell.api.root.create_entity(model, ifc_class='IfcBuildingStorey', name='Ground floor')
ifcopenshell.api.aggregate.assign_object(model, relating_object=project, products=[site])
ifcopenshell.api.aggregate.assign_object(model, relating_object=site, products=[building])
ifcopenshell.api.aggregate.assign_object(model, relating_object=building, products=[storey])

# The wall: placement, a swept-solid body, its storey (IfcRelContainedInSpatialStructure) and a property set.
wall = ifcopenshell.api.root.create_entity(model, ifc_class='IfcWall', name='W-01')
ifcopenshell.api.geometry.edit_object_placement(model, product=wall)
representation = ifcopenshell.api.geometry.add_wall_representation(model, context=body, length=5, height=2.8, thickness=0.2)
ifcopenshell.api.geometry.assign_representation(model, product=wall, representation=representation)
ifcopenshell.api.spatial.assign_container(model, relating_structure=storey, products=[wall])
pset = ifcopenshell.api.pset.add_pset(model, product=wall, name='Pset_WallCommon')
ifcopenshell.api.pset.edit_pset(model, pset=pset, properties={'FireRating': 'EI60'})

model.write('wall.ifc')
print(f'wall.ifc: {len(list(model))} instances')

Both files pass the schema check below with 0 issues, and both read back as one IfcWall named W-01 on “Ground floor”, with Pset_WallCommon.FireRating = 'EI60'. They are not the same file: each library chooses its own instance ids, GlobalIds and geometry.

Validating

There are three questions, and different tools answer them:

  1. Is it valid STEP and valid IFC? Syntax, then the schema: attribute types, required values, list sizes, inverse cardinalities, WHERE and UNIQUE rules. ifcopenshell.validate checks this, and the buildingSMART validation service runs it as its schema check.
  2. Does it follow the agreements? IFC has normative rules beyond the schema: implementer agreements and informal propositions that EXPRESS can’t state. The validation service checks these as Gherkin rules, and reports industry practices as warnings. It’s free (you sign in), takes IFC2X3, IFC4 and IFC4X3_ADD2 files up to 256 MB, and is open source (user guide).
  3. Does it contain what the project asked for? That’s an IDS check: chapter 6, with IFClite’s IDS validator or IfcOpenShell’s ifctester. If you write your own checker, convert measured values to the SI unit IDS uses before you compare: a length written as 1200 in a millimetre file is 1.2 against an IDS bound.
Do it in code: check a file against its schema

IfcOpenShell’s validator, as a script. The same works from the command line: python -m ifcopenshell.validate your.ifc. Run pip install ifcopenshell==0.8.5, then python validate.py your.ifc.

# Check a file against its schema, the way the buildingSMART validation service's schema check does. (For developers)
# pip install ifcopenshell==0.8.5, then: python validate.py your.ifc   (or: python -m ifcopenshell.validate your.ifc)
import sys

import ifcopenshell
import ifcopenshell.validate

model = ifcopenshell.open(sys.argv[1] if len(sys.argv) > 1 else 'wall.ifc')
logger = ifcopenshell.validate.json_logger()
# Types, cardinalities, inverse attributes, GlobalId uniqueness and form. The schema's WHERE rules come on top
# with express_rules=True (CLI: --rules), which also needs pytest installed.
ifcopenshell.validate.validate(model, logger)

for issue in logger.statements:
    message = '\n'.join(line.rstrip() for line in issue['message'].splitlines())
    print(f"{issue['level']}: {message}")
n = len(logger.statements)
print(f'{n} issue{"" if n == 1 else "s"}')

On chapter 1’s model it prints 0 issues. On chapter 7’s v2, where a window was duplicated together with its GlobalId, it finds the broken UNIQUE rule:

error: On instance:
    #1143=IfcWindow('0g3Wdycdn7afcUn962FX80',#104,'Window S2',$,$,#1180,#918,$,1.3,1.2,$,$,$)
                    ^^^^^^^^^^^^^^^^^^^^^^^^
Rule IfcRoot.UR1:
    The attribute GlobalId should be unique
Violated by:
    #1221=IfcWindow('0g3Wdycdn7afcUn962FX80',#104,'Window S2',$,$,#1180,#918,$,1.3,1.2,$,$,$)
                    ^^^^^^^^^^^^^^^^^^^^^^^^
1 issue

The WHERE rules aren’t checked by default. express_rules=True (on the command line --rules) adds them; in 0.8.5 that also needs pip install pytest, which the rule checker uses to explain a failed rule.

Validate what you write in CI, on every change, with a small set of real files from the tools your users have. A file that passes the schema can still be useless (no properties, no storeys), and a file that fails a WHERE rule usually still opens.

The libraries, compared

Open-source libraries that read and write IFC, as of 8 November 2026. Versions are the latest published; the facts come from each project’s own README, licence file and package metadata (links below the table).

Use it from Core Licence Schemas Writes Geometry
IfcOpenShell 0.8.5 / 0.9.0 Python, C++ C++ with Python bindings LGPL-3.0-or-later IFC2x3, IFC4, IFC4x1, IFC4x2, IFC4x3 ADD2 yes (ifcopenshell.api) Open CASCADE and CGAL
web-ifc 0.0.78 JavaScript, TypeScript C++ compiled to WebAssembly MPL-2.0 IFC2x3, IFC4, IFC4x3 yes its own C++ code
That Open Engine 3.6 (formerly IFC.js) TypeScript, in the browser with Three.js TypeScript, reads IFC through web-ifc MIT through web-ifc through web-ifc through web-ifc, stored as its Fragments format
xBIM (Xbim.Essentials 6.1) C#, .NET C#; geometry in C++/CLI CDDL-1.0 IFC2x3, IFC4, IFC4x3 (since 6.0) yes Open CASCADE
IFClite (parser 9.9.0) JavaScript, TypeScript, Rust Rust compiled to WebAssembly, TypeScript packages MPL-2.0 IFC2x3, IFC4, IFC4x3, IFCX (IFC 5) yes (@ifc-lite/create) its own kernel

Notes, one per library:

In Python, or when you need the widest coverage (geometry, editing, IDS, BCF, diffing) in one toolkit, use IfcOpenShell. In .NET, xBIM. In the browser there are two engines: web-ifc, with That Open’s viewer components on top, and IFClite. For IFCX, of these five only IFClite reads it today; buildingSMART’s own IFC 5 viewer does too. Whatever you pick, test with real files from the tools your users have.

Further reading: the IFC 4.3 documentation, IfcOpenShell’s documentation, and the OSArch community forum, where many of the people who write these libraries answer questions.