1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Rust binding for the shaderc library.
//!
//! The [shaderc](https://github.com/google/shaderc) library provides an API
//! for compiling GLSL/HLSL source code to SPIRV modules. It has been shipping
//! in the Android NDK since version r12b.
//!
//! This library uses [`build.rs`](build/build.rs) to automatically check out
//! and compile a copy of native C++ shaderc and link to the generated
//! artifacts, which requires `git`, `cmake`, and `python` existing in the
//! `PATH`.
//!
//! To turn off this feature, specify `--no-default-features` when building.
//! But then you will need to place a copy of the `shaderc_combined` static
//! library to the location (printed out in the warning message) that is
//! scanned by the linker.
//!
//! The build script also tries to check whether [Ninja](https://ninja-build.org/)
//! is available on `PATH`. If true, Ninja is used to compile native C++
//! shaderc. It is generally faster that way, and it does not suffer from the
//! `MAX_PATH` limitation that MSBuild, the default for building using MSVC,
//! has.
//!
//! # Examples
//!
//! Compile a shader into SPIR-V binary module and assembly text:
//!
//! ```
//! use shaderc;
//!
//! let source = "#version 310 es\n void EP() {}";
//!
//! let mut compiler = shaderc::Compiler::new().unwrap();
//! let mut options = shaderc::CompileOptions::new().unwrap();
//! options.add_macro_definition("EP", Some("main"));
//! let binary_result = compiler.compile_into_spirv(
//!     source, shaderc::ShaderKind::Vertex,
//!     "shader.glsl", "main", Some(&options)).unwrap();
//!
//! assert_eq!(Some(&0x07230203), binary_result.as_binary().first());
//!
//! let text_result = compiler.compile_into_spirv_assembly(
//!     source, shaderc::ShaderKind::Vertex,
//!     "shader.glsl", "main", Some(&options)).unwrap();
//!
//! assert!(text_result.as_text().starts_with("; SPIR-V\n"));
//! ```

extern crate libc;

#[cfg(test)]
#[macro_use]
extern crate assert_matches;

use libc::{c_char, c_int, c_void, size_t, int32_t, uint32_t, uint8_t};
use std::{error, fmt, ptr, result, slice, str};
use std::ffi::{CStr, CString};
use std::cell::RefCell;
use std::any::Any;
use std::panic;

mod ffi;

/// Error.
///
/// Each enumerants has an affixed string describing detailed reasons for
/// the error. The string can be empty in cases.
#[derive(Debug, PartialEq)]
pub enum Error {
    /// Compilation error.
    ///
    /// Contains the number of errors and detailed error string.
    CompilationError(u32, String),
    InternalError(String),
    InvalidStage(String),
    InvalidAssembly(String),
    NullResultObject(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::CompilationError(c, ref r) => {
                if r.is_empty() {
                    write!(f, "{} compilation error(s)", c)
                } else {
                    write!(f, "{} compilation error(s): {}", c, r)
                }
            }
            Error::InternalError(ref r) => {
                if r.is_empty() {
                    write!(f, "internal error")
                } else {
                    write!(f, "internal error: {}", r)
                }
            }
            Error::InvalidStage(ref r) => {
                if r.is_empty() {
                    write!(f, "invalid stage")
                } else {
                    write!(f, "invalid stage: {}", r)
                }
            }
            Error::InvalidAssembly(ref r) => {
                if r.is_empty() {
                    write!(f, "invalid assembly")
                } else {
                    write!(f, "invalid assembly: {}", r)
                }
            }
            Error::NullResultObject(ref r) => {
                if r.is_empty() {
                    write!(f, "null result object")
                } else {
                    write!(f, "null result object: {}", r)
                }
            }
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::CompilationError(_, _) => "compilation error",
            Error::InternalError(_) => "internal error",
            Error::InvalidStage(_) => "invalid stage",
            Error::InvalidAssembly(_) => "invalid assembly",
            Error::NullResultObject(_) => "null result object",
        }
    }
}

/// Compilation status.
pub type Result<T> = result::Result<T, Error>;

/// Target environment.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TargetEnv {
    /// Compile under Vulkan semantics.
    Vulkan,
    /// Compile under OpenGL semantics.
    OpenGL,
    /// Compile under OpenGL semantics, including compatibility profile functions.
    OpenGLCompat,
}

/// Source language.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceLanguage {
    GLSL,
    HLSL,
}

/// Resource kinds.
///
/// In Vulkan, resources are bound to the pipeline via descriptors with
/// numbered bindings and sets.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResourceKind {
    /// Image and image buffer.
    Image,
    /// Pure sampler.
    Sampler,
    /// Sampled texture in GLSL, and Shader Resource View in HLSL.
    Texture,
    /// Uniform Buffer Object (UBO) in GLSL. cbuffer in HLSL.
    Buffer,
    /// Shader Storage Buffer Object (SSBO) in GLSL.
    StorageBuffer,
    /// Unordered Access View in HLSL. (Writable storage image or storage buffer.)
    UnorderedAccessView,
}

/// Shader kind.
///
/// * The `<stage>` enumerants are forced shader kinds, which force the
///   compiler to compile the source code as the specified kind of shader,
///   regardless of `#pragma` directives in the source code.
/// * The `Default<stage>` enumerants are default shader kinds, which
///   allow the compiler to fall back to compile the source code as the
///   specified kind of shader when `#pragma` is not found in the source
///   code.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShaderKind {
    Vertex,
    Fragment,
    Compute,
    Geometry,
    TessControl,
    TessEvaluation,

    /// Deduce the shader kind from `#pragma` directives in the source code.
    ///
    /// Compiler will emit error if `#pragma` annotation is not found.
    InferFromSource,

    DefaultVertex,
    DefaultFragment,
    DefaultCompute,
    DefaultGeometry,
    DefaultTessControl,
    DefaultTessEvaluation,

    SpirvAssembly,
}

/// GLSL profile.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GlslProfile {
    /// Used iff GLSL version did not specify the profile
    None,
    Core,
    Compatibility,
    Es,
}

/// Optimization level.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OptimizationLevel {
    /// No optimization
    Zero,
    /// Optimize towards reducing code size
    Size,
    Performance,
}

/// Resource limit.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Limit {
    MaxLights,
    MaxClipPlanes,
    MaxTextureUnits,
    MaxTextureCoords,
    MaxVertexAttribs,
    MaxVertexUniformComponents,
    MaxVaryingFloats,
    MaxVertexTextureImageUnits,
    MaxCombinedTextureImageUnits,
    MaxTextureImageUnits,
    MaxFragmentUniformComponents,
    MaxDrawBuffers,
    MaxVertexUniformVectors,
    MaxVaryingVectors,
    MaxFragmentUniformVectors,
    MaxVertexOutputVectors,
    MaxFragmentInputVectors,
    MinProgramTexelOffset,
    MaxProgramTexelOffset,
    MaxClipDistances,
    MaxComputeWorkGroupCountX,
    MaxComputeWorkGroupCountY,
    MaxComputeWorkGroupCountZ,
    MaxComputeWorkGroupSizeX,
    MaxComputeWorkGroupSizeY,
    MaxComputeWorkGroupSizeZ,
    MaxComputeUniformComponents,
    MaxComputeTextureImageUnits,
    MaxComputeImageUniforms,
    MaxComputeAtomicCounters,
    MaxComputeAtomicCounterBuffers,
    MaxVaryingComponents,
    MaxVertexOutputComponents,
    MaxGeometryInputComponents,
    MaxGeometryOutputComponents,
    MaxFragmentInputComponents,
    MaxImageUnits,
    MaxCombinedImageUnitsAndFragmentOutputs,
    MaxCombinedShaderOutputResources,
    MaxImageSamples,
    MaxVertexImageUniforms,
    MaxTessControlImageUniforms,
    MaxTessEvaluationImageUniforms,
    MaxGeometryImageUniforms,
    MaxFragmentImageUniforms,
    MaxCombinedImageUniforms,
    MaxGeometryTextureImageUnits,
    MaxGeometryOutputVertices,
    MaxGeometryTotalOutputComponents,
    MaxGeometryUniformComponents,
    MaxGeometryVaryingComponents,
    MaxTessControlInputComponents,
    MaxTessControlOutputComponents,
    MaxTessControlTextureImageUnits,
    MaxTessControlUniformComponents,
    MaxTessControlTotalOutputComponents,
    MaxTessEvaluationInputComponents,
    MaxTessEvaluationOutputComponents,
    MaxTessEvaluationTextureImageUnits,
    MaxTessEvaluationUniformComponents,
    MaxTessPatchComponents,
    MaxPatchVertices,
    MaxTessGenLevel,
    MaxViewports,
    MaxVertexAtomicCounters,
    MaxTessControlAtomicCounters,
    MaxTessEvaluationAtomicCounters,
    MaxGeometryAtomicCounters,
    MaxFragmentAtomicCounters,
    MaxCombinedAtomicCounters,
    MaxAtomicCounterBindings,
    MaxVertexAtomicCounterBuffers,
    MaxTessControlAtomicCounterBuffers,
    MaxTessEvaluationAtomicCounterBuffers,
    MaxGeometryAtomicCounterBuffers,
    MaxFragmentAtomicCounterBuffers,
    MaxCombinedAtomicCounterBuffers,
    MaxAtomicCounterBufferSize,
    MaxTransformFeedbackBuffers,
    MaxTransformFeedbackInterleavedComponents,
    MaxCullDistances,
    MaxCombinedClipAndCullDistances,
    MaxSamples,
}

/// An opaque object managing all compiler states.
///
/// Creating an `Compiler` object has substantial resource costs; so it is
/// recommended to keep one object around for all tasks.
pub struct Compiler {
    raw: *mut ffi::ShadercCompiler,
}

fn propagate_panic<F, T>(f: F) -> T
where
    F: FnOnce() -> T,
{
    PANIC_ERROR.with(|panic_error| {
        *panic_error.borrow_mut() = None;
    });
    let result = f();
    let err = PANIC_ERROR.with(|panic_error| panic_error.borrow_mut().take());
    if let Some(err) = err {
        panic::resume_unwind(err)
    } else {
        result
    }
}

/// Returns a valid UTF-8 string from a slice of bytes.
///
/// A few shaderc functions have been observed to return invalid UTF-8 strings as
/// warning/error messages, and instead of panicking and aborting execution this
/// function can be used to convert the valid parts of the byte stream to
/// a UTF-8 string
fn safe_str_from_utf8(bytes: &[u8]) -> String {
    match str::from_utf8(bytes) {
        Ok(str) => str.to_string(),
        Err(err) => {
            if err.valid_up_to() > 0 {
                return format!(
                    "{} (followed by invalid UTF-8 characters)",
                    safe_str_from_utf8(&bytes[..err.valid_up_to()])
                );
            } else {
                return format!("invalid UTF-8 string: {}", err);
            }
        }
    }
}

impl Compiler {
    /// Returns an compiler object that can be used to compile SPIR-V modules.
    ///
    /// A return of `None` indicates that there was an error initializing
    /// the underlying compiler.
    pub fn new() -> Option<Compiler> {
        let p = unsafe { ffi::shaderc_compiler_initialize() };
        if p.is_null() {
            None
        } else {
            Some(Compiler { raw: p })
        }
    }

    fn handle_compilation_result(
        result: *mut ffi::ShadercCompilationResult,
        is_binary: bool,
    ) -> Result<CompilationArtifact> {
        let status = unsafe { ffi::shaderc_result_get_compilation_status(result) };
        if status == 0 {
            Ok(CompilationArtifact::new(result, is_binary))
        } else {
            let num_errors = unsafe { ffi::shaderc_result_get_num_errors(result) } as u32;
            let reason = unsafe {
                let p = ffi::shaderc_result_get_error_message(result);
                let bytes = CStr::from_ptr(p).to_bytes();
                safe_str_from_utf8(bytes)
            };
            match status {
                1 => Err(Error::InvalidStage(reason)),
                2 => Err(Error::CompilationError(num_errors, reason)),
                3 => Err(Error::InternalError(reason)),
                4 => Err(Error::NullResultObject(reason)),
                5 => Err(Error::InvalidAssembly(reason)),
                _ => panic!("unhandled shaderc error case"),
            }
        }
    }

    /// Compiles the given source string `source_text` to a SPIR-V binary
    /// module according to the given `additional_options`.
    ///
    /// The source string will be compiled into a SPIR-V binary module
    /// contained in a `CompilationArtifact` object if no error happens.
    ///
    /// The source string is treated as the given shader kind `shader_kind`.
    /// If `InferFromSource` is given, the compiler will try to deduce the
    /// shader kind from the source string via `#pragma` directives and a
    /// failure in deducing will generate an error. If the shader kind is
    /// set to one of the default shader kinds, the compiler will fall back
    /// to the default shader kind in case it failed to deduce the shader
    /// kind from the source string.
    ///
    /// `input_file_name` is a string used as a tag to identify the source
    /// string in cases like emitting error messages. It doesn't have to be
    /// a canonical "file name".
    ///
    /// `entry_point_name` is a string defines the name of the entry point
    /// to associate with the source string.
    pub fn compile_into_spirv(
        &mut self,
        source_text: &str,
        shader_kind: ShaderKind,
        input_file_name: &str,
        entry_point_name: &str,
        additional_options: Option<&CompileOptions>,
    ) -> Result<CompilationArtifact> {
        let source_size = source_text.len();
        let c_source = CString::new(source_text).expect("cannot convert source_text to c string");
        let c_file =
            CString::new(input_file_name).expect("cannot convert input_file_name to c string");
        let c_entry_point =
            CString::new(entry_point_name).expect("cannot convert entry_point_name to c string");
        propagate_panic(|| {
            let result = unsafe {
                ffi::shaderc_compile_into_spv(
                    self.raw,
                    c_source.as_ptr(),
                    source_size,
                    shader_kind as int32_t,
                    c_file.as_ptr(),
                    c_entry_point.as_ptr(),
                    additional_options.map_or(ptr::null(), |ref o| o.raw),
                )
            };
            Compiler::handle_compilation_result(result, true)
        })
    }

    /// Like `compile_into_spirv` but the result contains SPIR-V assembly text
    /// instead of a SPIR-V binary module.
    ///
    /// The output SPIR-V assembly string will be of the format defined in
    /// the [SPIRV-Tools](https://github.com/KhronosGroup/SPIRV-Tools/blob/master/syntax.md)
    /// project.
    pub fn compile_into_spirv_assembly(
        &mut self,
        source_text: &str,
        shader_kind: ShaderKind,
        input_file_name: &str,
        entry_point_name: &str,
        additional_options: Option<&CompileOptions>,
    ) -> Result<CompilationArtifact> {
        let source_size = source_text.len();
        let c_source = CString::new(source_text).expect("cannot convert source_text to c string");
        let c_file =
            CString::new(input_file_name).expect("cannot convert input_file_name to c string");
        let c_entry_point =
            CString::new(entry_point_name).expect("cannot convert entry_point_name to c string");
        propagate_panic(|| {
            let result = unsafe {
                ffi::shaderc_compile_into_spv_assembly(
                    self.raw,
                    c_source.as_ptr(),
                    source_size,
                    shader_kind as int32_t,
                    c_file.as_ptr(),
                    c_entry_point.as_ptr(),
                    additional_options.map_or(ptr::null(), |ref o| o.raw),
                )
            };
            Compiler::handle_compilation_result(result, false)
        })
    }

    /// Like `compile_into_spirv` but the result contains preprocessed source
    /// code instead of a SPIR-V binary module.
    pub fn preprocess(
        &mut self,
        source_text: &str,
        input_file_name: &str,
        entry_point_name: &str,
        additional_options: Option<&CompileOptions>,
    ) -> Result<CompilationArtifact> {
        let source_size = source_text.len();
        let c_source = CString::new(source_text).expect("cannot convert source to c string");
        let c_file =
            CString::new(input_file_name).expect("cannot convert input_file_name to c string");
        let c_entry_point =
            CString::new(entry_point_name).expect("cannot convert entry_point_name to c string");
        propagate_panic(|| {
            let result = unsafe {
                ffi::shaderc_compile_into_preprocessed_text(
                    self.raw,
                    c_source.as_ptr(),
                    source_size,
                    // Stage doesn't matter for preprocess
                    ShaderKind::Vertex as int32_t,
                    c_file.as_ptr(),
                    c_entry_point.as_ptr(),
                    additional_options.map_or(ptr::null(), |ref o| o.raw),
                )
            };
            Compiler::handle_compilation_result(result, false)
        })
    }

    /// Assembles the given SPIR-V assembly string `source_assembly` into a
    /// SPIR-V binary module according to the given `additional_options`.
    ///
    /// The input SPIR-V assembly string should be of the format defined in
    /// the [SPIRV-Tools](https://github.com/KhronosGroup/SPIRV-Tools/blob/master/syntax.md)
    /// project.
    ///
    /// For options specified in `additional_options`, the assembling will
    /// only pick those ones suitable for assembling.
    pub fn assemble(
        &mut self,
        source_assembly: &str,
        additional_options: Option<&CompileOptions>,
    ) -> Result<CompilationArtifact> {
        let source_size = source_assembly.len();
        let c_source =
            CString::new(source_assembly).expect("cannot convert source_assembly to c string");
        propagate_panic(|| {
            let result = unsafe {
                ffi::shaderc_assemble_into_spv(
                    self.raw,
                    c_source.as_ptr(),
                    source_size,
                    additional_options.map_or(ptr::null(), |ref o| o.raw),
                )
            };
            Compiler::handle_compilation_result(result, true)
        })
    }
}

impl Drop for Compiler {
    fn drop(&mut self) {
        unsafe { ffi::shaderc_compiler_release(self.raw) }
    }
}

/// An opaque object managing options to compilation.
pub struct CompileOptions<'a> {
    raw: *mut ffi::ShadercCompileOptions,
    f: Option<
        Box<Fn(&str, IncludeType, &str, usize) -> result::Result<ResolvedInclude, String> + 'a>,
    >,
}

/// Identifies the type of include directive. `Relative` is for include directives of the form
/// `#include "..."`, and `Standard` is for include directives of the form `#include <...>`.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Debug)]
pub enum IncludeType {
    Relative,
    Standard,
}

/// A representation of a successfully resolved include directive, containing the name of the include
/// and its contents.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Debug)]
pub struct ResolvedInclude {
    /// A name uniquely identifying the resolved include. Typically the absolute path of the file.
    ///
    /// This name is used in error messages and to disambiguate different includes.
    ///
    /// This field must not be empty. Compilation will panic if an empty string is provided.
    pub resolved_name: String,
    /// The content of the include to substitute the include directive with.
    pub content: String,
}

thread_local! {
    static PANIC_ERROR: RefCell<Option<Box<Any + Send + 'static>>> = RefCell::new(None);
}

impl<'a> CompileOptions<'a> {
    /// Returns a default-initialized compilation options object.
    ///
    /// The default options are:
    /// * Target environment: Vulkan
    /// * Source language: GLSL
    ///
    /// A return of `None` indicates that there was an error initializing
    /// the underlying options object.
    pub fn new() -> Option<CompileOptions<'a>> {
        let p = unsafe { ffi::shaderc_compile_options_initialize() };
        if p.is_null() {
            None
        } else {
            Some(CompileOptions { raw: p, f: None })
        }
    }

    /// Returns a copy of the given compilation options object.
    ///
    /// A return of `None` indicates that there was an error copying
    /// the underlying options object.
    pub fn clone(&self) -> Option<CompileOptions> {
        let p = unsafe { ffi::shaderc_compile_options_clone(self.raw) };
        if p.is_null() {
            None
        } else {
            Some(CompileOptions { raw: p, f: None })
        }
    }

    /// Sets the target enviroment to `env`, affecting which warnings or errors
    /// will be issued.
    ///
    /// The default is Vulkan if not set.
    ///
    /// `version` will be used for distinguishing between different versions
    /// of the target environment. "0" is the only supported value right now.
    pub fn set_target_env(&mut self, env: TargetEnv, version: u32) {
        unsafe { ffi::shaderc_compile_options_set_target_env(self.raw, env as int32_t, version) }
    }

    /// Sets the source language.
    ///
    /// The default is GLSL if not set.
    pub fn set_source_language(&mut self, language: SourceLanguage) {
        unsafe { ffi::shaderc_compile_options_set_source_language(self.raw, language as int32_t) }
    }

    /// Forces the GLSL language `version` and `profile`.
    ///
    /// The version number is the same as would appear in the `#version`
    /// directive in the source. Version and profile specified here
    /// overrides the `#version` directive in the source code. Use
    /// `GlslProfile::None` for GLSL versions that do not define profiles,
    /// e.g., version below 150.
    pub fn set_forced_version_profile(&mut self, version: u32, profile: GlslProfile) {
        unsafe {
            ffi::shaderc_compile_options_set_forced_version_profile(
                self.raw,
                version as c_int,
                profile as int32_t,
            )
        }
    }

    /// Sets the callback for handling the `#include` directive.
    ///
    /// The arguments to the callback are the name of the source being requested,
    /// the type of include directive (`Relative` for `#include "foo"`, `Standard` for `#include <foo>`),
    /// the name of the source containing the directive and the current include depth from the original
    /// source.
    ///
    /// The return value of the callback should be `Ok` if the source was successfully found,
    /// and an `Err` containing some suitable error message to display otherwise. If the result is
    /// `Ok`, the `resolved_name` of the `ResolvedInclude` must be non-empty. All strings returned
    /// from the callback must be convertible to `CString`s, i.e. they must not contain the null
    /// character. If these conditions are not met compilation will panic.
    ///
    /// Behaviour note: If `Err` is returned for a `Relative` include request, the callback will be
    /// tried again with `Standard`, which is similar to include directive behaviour in C.
    pub fn set_include_callback<F>(&mut self, f: F)
    where
        F: Fn(&str, IncludeType, &str, usize) -> result::Result<ResolvedInclude, String> + 'a,
    {
        use std::mem;

        let f = Box::new(f);
        let f_ptr = &*f as *const F;
        self.f = Some(
            f
                as Box<
                    Fn(&str, IncludeType, &str, usize) -> result::Result<ResolvedInclude, String>
                        + 'a,
                >,
        );
        unsafe {
            ffi::shaderc_compile_options_set_include_callbacks(
                self.raw,
                resolver::<'a, F>,
                releaser,
                f_ptr as *const c_void as *mut c_void,
            );
        }

        struct OkResultWrapper {
            source_name: CString,
            content: CString,
            wrapped: ffi::shaderc_include_result,
        }

        struct ErrResultWrapper {
            error_message: CString,
            wrapped: ffi::shaderc_include_result,
        }

        extern "C" fn resolver<'a, F>(
            user_data: *mut c_void,
            requested_source: *const c_char,
            type_: c_int,
            requesting_source: *const c_char,
            include_depth: size_t,
        ) -> *mut ffi::shaderc_include_result
        where
            F: Fn(&str, IncludeType, &str, usize) -> result::Result<ResolvedInclude, String> + 'a,
        {
            let result = panic::catch_unwind(move || {
                let f = unsafe { &*(user_data as *const F) };
                let requested_source =
                    unsafe { CStr::from_ptr(requested_source).to_string_lossy() };
                let type_ = match type_ {
                    0 => IncludeType::Relative,
                    1 => IncludeType::Standard,
                    x => panic!(
                        "include callback: unknown include type returned from libshaderc: {}",
                        x
                    ),
                };
                let requesting_source =
                    unsafe { CStr::from_ptr(requesting_source).to_string_lossy() };
                match f(&requested_source, type_, &requesting_source, include_depth) {
                    Ok(ResolvedInclude {
                        resolved_name,
                        content,
                    }) => {
                        if resolved_name.len() == 0 {
                            panic!("include callback: empty strings for resolved include names not allowed");
                        }
                        let mut result = Box::new(OkResultWrapper {
                            source_name: CString::new(resolved_name).expect("include callback: could not convert resolved source name to a c string"),
                            content: CString::new(content).expect("include callback: could not convert content string to a c string"),
                            wrapped: unsafe { mem::zeroed() },
                        });
                        result.wrapped = ffi::shaderc_include_result {
                            source_name: result.source_name.as_ptr(),
                            source_name_length: result.source_name.as_bytes().len(),
                            content: result.content.as_ptr(),
                            content_length: result.content.as_bytes().len(),
                            user_data: &mut *result as *mut OkResultWrapper as *mut c_void,
                        };
                        let r = &mut result.wrapped as *mut ffi::shaderc_include_result;
                        mem::forget(result);
                        r
                    }
                    Err(error_message) => {
                        let mut result = Box::new(ErrResultWrapper {
                            error_message: CString::new(error_message).expect(
                                "include callback: could not convert error message to a c string",
                            ),
                            wrapped: unsafe { mem::zeroed() },
                        });
                        result.wrapped = ffi::shaderc_include_result {
                            source_name: CStr::from_bytes_with_nul(b"\0").unwrap().as_ptr(),
                            source_name_length: 0,
                            content: result.error_message.as_ptr(),
                            content_length: result.error_message.as_bytes().len(),
                            user_data: &mut *result as *mut ErrResultWrapper as *mut c_void,
                        };
                        let r = &mut result.wrapped as *mut ffi::shaderc_include_result;
                        mem::forget(result);
                        r
                    }
                }
            });
            match result {
                Ok(r) => r,
                Err(e) => {
                    PANIC_ERROR.with(|panic_error| {
                        *panic_error.borrow_mut() = Some(e);
                    });
                    let mut result = Box::new(ErrResultWrapper {
                        error_message: CString::new("").unwrap(),
                        wrapped: unsafe { mem::zeroed() },
                    });
                    result.wrapped = ffi::shaderc_include_result {
                        source_name: CStr::from_bytes_with_nul(b"\0").unwrap().as_ptr(),
                        source_name_length: 0,
                        content: result.error_message.as_ptr(),
                        content_length: 0,
                        user_data: &mut *result as *mut ErrResultWrapper as *mut c_void,
                    };
                    let r = &mut result.wrapped as *mut ffi::shaderc_include_result;
                    mem::forget(result);
                    r
                }
            }
        }

        extern "C" fn releaser(_: *mut c_void, include_result: *mut ffi::shaderc_include_result) {
            let user_data = unsafe { &*include_result }.user_data;
            if unsafe { &*include_result }.source_name_length == 0 {
                let wrapper = unsafe { Box::from_raw(user_data as *mut ErrResultWrapper) };
                drop(wrapper);
            } else {
                let wrapper = unsafe { Box::from_raw(user_data as *mut OkResultWrapper) };
                drop(wrapper);
            }
        }
    }

    /// Sets the resource `limit` to the given `value`.
    pub fn set_limit(&mut self, limit: Limit, value: i32) {
        unsafe {
            ffi::shaderc_compile_options_set_limit(self.raw, limit as int32_t, value as c_int)
        }
    }

    /// Sets whether the compiler should automatically assign bindings to uniforms
    /// that aren't already explicitly bound in the shader source.
    pub fn set_auto_bind_uniforms(&mut self, auto_bind: bool) {
        unsafe {
            ffi::shaderc_compile_options_set_auto_bind_uniforms(self.raw, auto_bind);
        }
    }

    /// Sets whether the compiler should use HLSL IO mapping rules for bindings.
    ///
    /// Defaults to false.
    pub fn set_hlsl_io_mapping(&mut self, hlsl_iomap: bool) {
        unsafe {
            ffi::shaderc_compile_options_set_hlsl_io_mapping(self.raw, hlsl_iomap);
        }
    }

    /// Sets whether the compiler should determine block member offsets using HLSL
    /// packing rules instead of standard GLSL rules.
    ///
    /// Defaults to false. Only affects GLSL compilation. HLSL rules are always
    /// used when compiling HLSL.
    pub fn set_hlsl_offsets(&mut self, hlsl_offsets: bool) {
        unsafe {
            ffi::shaderc_compile_options_set_hlsl_offsets(self.raw, hlsl_offsets);
        }
    }

    /// Sets the base binding number used for for a resource type when automatically
    /// assigning bindings.
    ///
    /// For GLSL compilation, sets the lowest automatically assigned number.
    /// For HLSL compilation, the regsiter number assigned to the resource is added
    /// to this specified base.
    pub fn set_binding_base(&mut self, resource_kind: ResourceKind, base: u32) {
        unsafe {
            ffi::shaderc_compile_options_set_binding_base(self.raw, resource_kind as int32_t, base);
        }
    }

    /// Like `set_binding_base`, but only takes effect when compiling the given shader stage.
    pub fn set_binding_base_for_stage(
        &mut self,
        shader_kind: ShaderKind,
        resource_kind: ResourceKind,
        base: u32,
    ) {
        unsafe {
            ffi::shaderc_compile_options_set_binding_base_for_stage(
                self.raw,
                shader_kind as int32_t,
                resource_kind as int32_t,
                base,
            );
        }
    }

    /// Sets a descriptor set and binding for an HLSL register in all shader stages.
    pub fn set_hlsl_register_set_and_binding(&mut self, register: &str, set: &str, binding: &str) {
        let c_register = CString::new(register).expect("cannot convert string to c string");
        let c_set = CString::new(set).expect("cannot convert string to c string");
        let c_binding = CString::new(binding).expect("cannot convert string to c string");
        unsafe {
            ffi::shaderc_compile_options_set_hlsl_register_set_and_binding(
                self.raw,
                c_register.as_ptr(),
                c_set.as_ptr(),
                c_binding.as_ptr(),
            );
        }
    }

    /// Like `set_hlsl_register_set_and_binding`, but only takes effect when compiling
    /// the given shader stage.
    pub fn set_hlsl_register_set_and_binding_for_stage(
        &mut self,
        kind: ShaderKind,
        register: &str,
        set: &str,
        binding: &str,
    ) {
        let c_register = CString::new(register).expect("cannot convert string to c string");
        let c_set = CString::new(set).expect("cannot convert string to c string");
        let c_binding = CString::new(binding).expect("cannot convert string to c string");
        unsafe {
            ffi::shaderc_compile_options_set_hlsl_register_set_and_binding_for_stage(
                self.raw,
                kind as int32_t,
                c_register.as_ptr(),
                c_set.as_ptr(),
                c_binding.as_ptr(),
            );
        }
    }

    /// Adds a predefined macro to the compilation options.
    ///
    /// This has the same effect as passing `-Dname=value` to the command-line
    /// compiler.  If `value` is `None`, it has the same effect as passing
    /// `-Dname` to the command-line compiler. If a macro definition with the
    /// same name has previously been added, the value is replaced with the
    /// new value.
    pub fn add_macro_definition(&mut self, name: &str, value: Option<&str>) {
        let c_name = CString::new(name).expect("cannot convert name to c string");
        if value.is_some() {
            let value = value.unwrap();
            let c_value = CString::new(value).expect("cannot convert value to c string");
            unsafe {
                ffi::shaderc_compile_options_add_macro_definition(
                    self.raw,
                    c_name.as_ptr(),
                    name.len(),
                    c_value.as_ptr(),
                    value.len(),
                )
            }
        } else {
            unsafe {
                ffi::shaderc_compile_options_add_macro_definition(
                    self.raw,
                    c_name.as_ptr(),
                    name.len(),
                    ptr::null(),
                    0,
                )
            }
        }
    }

    /// Sets the optimization level to `level`.
    ///
    /// If mulitple invocations for this method, only the last one takes effect.
    pub fn set_optimization_level(&mut self, level: OptimizationLevel) {
        unsafe { ffi::shaderc_compile_options_set_optimization_level(self.raw, level as int32_t) }
    }

    /// Sets the compiler mode to generate debug information in the output.
    pub fn set_generate_debug_info(&mut self) {
        unsafe { ffi::shaderc_compile_options_set_generate_debug_info(self.raw) }
    }

    /// Sets the compiler mode to suppress warnings.
    ///
    /// This overrides warnings-as-errors mode: when both suppress-warnings and
    /// warnings-as-errors modes are turned on, warning messages will be
    /// inhibited, and will not be emitted as error messages.
    pub fn set_suppress_warnings(&mut self) {
        unsafe { ffi::shaderc_compile_options_set_suppress_warnings(self.raw) }
    }

    /// Sets the compiler mode to treat all warnings as errors.
    ///
    /// Note that the suppress-warnings mode overrides this.
    pub fn set_warnings_as_errors(&mut self) {
        unsafe { ffi::shaderc_compile_options_set_warnings_as_errors(self.raw) }
    }
}

impl<'a> Drop for CompileOptions<'a> {
    fn drop(&mut self) {
        unsafe { ffi::shaderc_compile_options_release(self.raw) }
    }
}

/// An opaque object containing the results of compilation.
pub struct CompilationArtifact {
    raw: *mut ffi::ShadercCompilationResult,
    is_binary: bool,
}

impl CompilationArtifact {
    fn new(result: *mut ffi::ShadercCompilationResult, is_binary: bool) -> CompilationArtifact {
        CompilationArtifact {
            raw: result,
            is_binary: is_binary,
        }
    }

    /// Returns the number of bytes of the compilation output data.
    pub fn len(&self) -> usize {
        unsafe { ffi::shaderc_result_get_length(self.raw) }
    }

    /// Returns the compilation output data as a binary slice.
    ///
    /// # Panics
    ///
    /// This method will panic if the compilation does not generate a
    /// binary output.
    pub fn as_binary(&self) -> &[u32] {
        if !self.is_binary {
            panic!("not binary result")
        }

        assert_eq!(0, self.len() % 4);
        let num_words = self.len() / 4;

        unsafe {
            let p = ffi::shaderc_result_get_bytes(self.raw);
            slice::from_raw_parts(p as *const uint32_t, num_words)
        }
    }

    /// Returns the compilation output data as a binary slice.
    /// This method return a &[u8] that implement the Read trait.
    ///
    /// # Panics
    ///
    /// This method will panic if the compilation does not generate a
    /// binary output.
    pub fn as_binary_u8(&self) -> &[u8] {
        if !self.is_binary {
            panic!("not binary result")
        }

        assert_eq!(0, self.len() % 4);

        unsafe {
            let p = ffi::shaderc_result_get_bytes(self.raw);
            slice::from_raw_parts(p as *const uint8_t, self.len())
        }
    }

    /// Returns the compilation output data as a text string.
    ///
    /// # Panics
    ///
    /// This method will panic if the compilation does not generate a
    /// text output.
    pub fn as_text(&self) -> String {
        if self.is_binary {
            panic!("not text result")
        }
        unsafe {
            let p = ffi::shaderc_result_get_bytes(self.raw);
            let bytes = CStr::from_ptr(p).to_bytes();
            str::from_utf8(bytes)
                .ok()
                .expect("invalid utf-8 string")
                .to_string()
        }
    }

    /// Returns the number of warnings generated during the compilation.
    pub fn get_num_warnings(&self) -> u32 {
        (unsafe { ffi::shaderc_result_get_num_warnings(self.raw) }) as u32
    }

    /// Returns the detailed warnings as a string.
    pub fn get_warning_messages(&self) -> String {
        unsafe {
            let p = ffi::shaderc_result_get_error_message(self.raw);
            let bytes = CStr::from_ptr(p).to_bytes();
            safe_str_from_utf8(bytes)
        }
    }
}

impl Drop for CompilationArtifact {
    fn drop(&mut self) {
        unsafe { ffi::shaderc_result_release(self.raw) }
    }
}

/// Returns the version and revision of the SPIR-V generated by this library.
///
/// The version number is a 32-bit word with the following four bytes
/// (high-order to low-order): `0 | Major Number | Minor Number | 0`.
/// So version 1.00 is of value 0x00010000.
pub fn get_spirv_version() -> (u32, u32) {
    let mut version: i32 = 0;
    let mut revision: i32 = 0;
    unsafe { ffi::shaderc_get_spv_version(&mut version, &mut revision) };
    (version as u32, revision as u32)
}

/// Parses the version and profile from the given `string`.
///
/// The string should contain both version and profile, like: `450core`.
/// Returns `None` if the string can not be parsed.
pub fn parse_version_profile(string: &str) -> Option<(u32, GlslProfile)> {
    let mut version: i32 = 0;
    let mut profile: i32 = 0;
    let c_string = CString::new(string).expect("cannot convert string to c string");
    let result = unsafe {
        ffi::shaderc_parse_version_profile(c_string.as_ptr(), &mut version, &mut profile)
    };
    if result == false {
        None
    } else {
        let p = match profile {
            0 => GlslProfile::None,
            1 => GlslProfile::Core,
            2 => GlslProfile::Compatibility,
            3 => GlslProfile::Es,
            _ => panic!("internal error: unhandled profile"),
        };
        Some((version as u32, p))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    static VOID_MAIN: &'static str = "#version 310 es\n void main() {}";
    static VOID_E: &'static str = "#version 310 es\n void E() {}";
    static EXTRA_E: &'static str = "#version 310 es\n E\n void main() {}";
    static IFDEF_E: &'static str = "#version 310 es\n #ifdef E\n void main() {}\n\
                                    #else\n #error\n #endif";
    static HLSL_VERTEX: &'static str = "float4 main(uint index: SV_VERTEXID): SV_POSITION\n\
                                        { return float4(1., 2., 3., 4.); }";
    static TWO_ERROR: &'static str = "#version 310 es\n #error one\n #error two\n void main() {}";
    static TWO_ERROR_MSG: &'static str = "shader.glsl:2: error: '#error' : one\n\
                                          shader.glsl:3: error: '#error' : two\n";
    static ONE_WARNING: &'static str = "#version 400\n\
                                        layout(location = 0) attribute float x;\n void main() {}";
    static ONE_WARNING_MSG: &'static str = "\
shader.glsl:2: warning: attribute deprecated in version 130; may be removed in future release
";
    static DEBUG_INFO: &'static str = "#version 140\n \
                                       void main() {\n vec2 debug_info_sample = vec2(1.0);\n }";
    static CORE_PROFILE: &'static str = "void main() {\n gl_ClipDistance[0] = 5.;\n }";

    static TWO_FN: &'static str = "\
#version 450
layout(location=0) in  int inVal;
layout(location=0) out int outVal;
int foo(int a) { return a; }
void main() { outVal = foo(inVal); }";

    /// A shader that compiles under OpenGL compatibility but not core profile rules.
    static COMPAT_FRAG: &'static str = "\
#version 100
layout(binding = 0) uniform highp sampler2D tex;
void main() {
    gl_FragColor = texture2D(tex, vec2(0.));
}";

    static VOID_MAIN_ASSEMBLY: &'static str = "\
; SPIR-V
; Version: 1.0
; Generator: Google Shaderc over Glslang; 7
; Bound: 6
; Schema: 0
               OpCapability Shader
          %1 = OpExtInstImport \"GLSL.std.450\"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Vertex %main \"main\"
               OpSource ESSL 310
               OpSourceExtension \"GL_GOOGLE_cpp_style_line_directive\"
               OpSourceExtension \"GL_GOOGLE_include_directive\"
               OpName %main \"main\"
       %void = OpTypeVoid
          %3 = OpTypeFunction %void
       %main = OpFunction %void None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
";

    static UNIFORMS_NO_BINDINGS: &'static str = "\
#version 450
#extension GL_ARB_sparse_texture2 : enable
uniform texture2D my_tex;
uniform sampler my_sam;
layout(rgba32f) uniform image2D my_img;
layout(rgba32f) uniform imageBuffer my_imbuf;
uniform block { float x; float y; } my_ubo;
void main() {
  texture(sampler2D(my_tex,my_sam),vec2(1.0));
  vec4 t;
  sparseImageLoadARB(my_img,ivec2(0),t);
  imageLoad(my_imbuf,42);
  float x = my_ubo.x;
}";

    static GLSL_WEIRD_PACKING: &'static str = "\
#version 450
buffer B { float x; vec3 foo; } my_ssbo;
void main() { my_ssbo.x = 1.0; }";

    #[test]
    fn test_compile_vertex_shader_into_spirv() {
        let mut c = Compiler::new().unwrap();
        let result =
            c.compile_into_spirv(VOID_MAIN, ShaderKind::Vertex, "shader.glsl", "main", None)
                .unwrap();
        assert!(result.len() > 20);
        assert!(result.as_binary().first() == Some(&0x07230203));
        let function_end_word: u32 = (1 << 16) | 56;
        assert!(result.as_binary().last() == Some(&function_end_word));
    }

    #[test]
    fn test_compile_vertex_shader_into_spirv_assembly() {
        let mut c = Compiler::new().unwrap();
        let result = c.compile_into_spirv_assembly(
            VOID_MAIN,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            None,
        ).unwrap();
        assert_eq!(VOID_MAIN_ASSEMBLY, result.as_text());
    }

    #[test]
    fn test_preprocess() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.add_macro_definition("E", Some("main"));
        let result = c.preprocess(VOID_E, "shader.glsl", "main", Some(&options))
            .unwrap();
        assert_eq!("#version 310 es\n void main(){ }\n", result.as_text());
    }

    #[test]
    fn test_assemble() {
        let mut c = Compiler::new().unwrap();
        let result = c.assemble(VOID_MAIN_ASSEMBLY, None).unwrap();
        assert!(result.len() > 20);
        assert!(result.as_binary().first() == Some(&0x07230203));
        let function_end_word: u32 = (1 << 16) | 56;
        assert!(result.as_binary().last() == Some(&function_end_word));
    }

    #[test]
    fn test_compile_options_add_macro_definition_normal_value() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.add_macro_definition("E", Some("main"));
        let result = c.compile_into_spirv_assembly(
            VOID_E,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert_eq!(VOID_MAIN_ASSEMBLY, result.as_text());
    }

    #[test]
    fn test_compile_options_add_macro_definition_empty_value() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.add_macro_definition("E", Some(""));
        let result = c.compile_into_spirv_assembly(
            EXTRA_E,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert_eq!(VOID_MAIN_ASSEMBLY, result.as_text());
    }

    #[test]
    fn test_compile_options_add_macro_definition_no_value() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.add_macro_definition("E", None);
        let result = c.compile_into_spirv_assembly(
            IFDEF_E,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert_eq!(VOID_MAIN_ASSEMBLY, result.as_text());
    }

    #[test]
    fn test_compile_options_clone() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.add_macro_definition("E", None);
        let o = options.clone().unwrap();
        let result = c.compile_into_spirv_assembly(
            IFDEF_E,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&o),
        ).unwrap();
        assert_eq!(VOID_MAIN_ASSEMBLY, result.as_text());
    }

    #[test]
    fn test_compile_options_set_source_language() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_source_language(SourceLanguage::HLSL);
        let result = c.compile_into_spirv(
            HLSL_VERTEX,
            ShaderKind::Vertex,
            "shader.hlsl",
            "main",
            Some(&options),
        ).unwrap();
        assert!(result.len() > 20);
        assert!(result.as_binary().first() == Some(&0x07230203));
        let function_end_word: u32 = (1 << 16) | 56;
        assert!(result.as_binary().last() == Some(&function_end_word));
    }

    #[test]
    fn test_compile_options_set_generate_debug_info() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_generate_debug_info();
        let result = c.compile_into_spirv_assembly(
            DEBUG_INFO,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert!(result.as_text().contains("debug_info_sample"));
    }

    #[test]
    fn test_compile_options_set_optimization_level_zero() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_optimization_level(OptimizationLevel::Zero);
        let result = c.compile_into_spirv_assembly(
            DEBUG_INFO,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert!(result.as_text().contains("OpName"));
        assert!(result.as_text().contains("OpSource"));
    }

    #[test]
    fn test_compile_options_set_optimization_level_size() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_optimization_level(OptimizationLevel::Size);
        let result = c.compile_into_spirv_assembly(
            TWO_FN,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert!(!result.as_text().contains("OpFunctionCall"));
    }

    #[test]
    fn test_compile_options_set_optimization_level_performance() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_optimization_level(OptimizationLevel::Performance);
        let result = c.compile_into_spirv_assembly(
            TWO_FN,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert!(!result.as_text().contains("OpFunctionCall"));
    }

    #[test]
    fn test_compile_options_set_forced_version_profile_ok() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_forced_version_profile(450, GlslProfile::Core);
        let result = c.compile_into_spirv(
            CORE_PROFILE,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert!(result.len() > 20);
        assert!(result.as_binary().first() == Some(&0x07230203));
        let function_end_word: u32 = (1 << 16) | 56;
        assert!(result.as_binary().last() == Some(&function_end_word));
    }

    #[test]
    fn test_compile_options_set_forced_version_profile_err() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_forced_version_profile(310, GlslProfile::Es);
        let result = c.compile_into_spirv(
            CORE_PROFILE,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        );
        assert!(result.is_err());
        assert_matches!(result.err(),
                        Some(Error::CompilationError(3, ref s))
                            if s.contains("error: 'gl_ClipDistance' : undeclared identifier"));
    }

    #[test]
    #[should_panic(expected = "Panic in include resolver!")]
    fn test_include_directive_panic() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_include_callback(|_, _, _, _| panic!("Panic in include resolver!"));
        drop(c.compile_into_spirv_assembly(
            r#"
            #version 400
            #include "foo.glsl"
            "#,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ));
    }

    #[test]
    fn test_include_directive_err() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_include_callback(|name, _, _, _| {
            Err(format!("Couldn't find header \"{}\"", name))
        });
        let result = c.compile_into_spirv_assembly(
            r#"
            #version 400
            #include "foo.glsl"
            "#,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        );
        assert!(result.is_err());
        assert_matches!(result.err(),
            Some(Error::CompilationError(1, ref s))
            if s.contains("Couldn't find header \"foo.glsl\""));
    }

    #[test]
    fn test_include_directive_success() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_include_callback(|name, type_, _, _| {
            if name == "foo.glsl" && type_ == IncludeType::Relative {
                Ok(ResolvedInclude {
                    resolved_name: "std/foo.glsl".to_string(),
                    content: r#"
                    #ifndef FOO_H
                    #define FOO_H
                    void main() {}
                    #endif
                    "#.to_string(),
                })
            } else {
                Err(format!("Couldn't find header \"{}\"", name))
            }
        });
        let result = c.compile_into_spirv_assembly(
            r#"
            #version 400
            #include "foo.glsl"
            #include "foo.glsl"
            "#,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        );
        assert_matches!(result.err(), None);
    }

    #[test]
    fn test_compile_options_set_suppress_warnings() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_suppress_warnings();
        let result = c.compile_into_spirv(
            ONE_WARNING,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap();
        assert_eq!(0, result.get_num_warnings());
    }

    #[test]
    fn test_compile_options_set_warnings_as_errors() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_warnings_as_errors();
        let result = c.compile_into_spirv(
            ONE_WARNING,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        );
        assert!(result.is_err());
        assert_matches!(result.err(),
                        Some(Error::CompilationError(1, ref s))
                            if s.contains("error: attribute deprecated in version 130;"));
    }

    #[test]
    fn test_compile_options_set_target_env_err_vulkan() {
        let mut c = Compiler::new().unwrap();
        let result = c.compile_into_spirv(
            COMPAT_FRAG,
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            None,
        );
        assert!(result.is_err());
        assert_matches!(result.err(),
                        Some(Error::CompilationError(4, ref s))
                            if s.contains("error: #version: ES shaders for Vulkan SPIR-V \
                                           require version 310 or higher"));
    }

    #[test]
    fn test_compile_options_set_target_env_err_opengl() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_target_env(TargetEnv::OpenGL, 0);
        let result = c.compile_into_spirv(
            COMPAT_FRAG,
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            Some(&options),
        );
        assert!(result.is_err());
        assert_matches!(result.err(),
                        Some(Error::CompilationError(3, ref s))
                            if s.contains("error: #version: ES shaders for OpenGL SPIR-V \
                                           are not supported"));
    }

    /// Returns a fragment shader accessing a texture with the given offset.
    macro_rules! texture_offset {
        ($offset:expr) => ({
            let mut s = "#version 450
                         layout (binding=0) uniform sampler1D tex;
                         void main() {
                            vec4 x = textureOffset(tex, 1., ".to_string();
            s.push_str(stringify!($offset));
            s.push_str(");\n}");
            s
        })
    }

    #[test]
    fn test_compile_options_set_limit() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        assert!(c.compile_into_spirv(
            &texture_offset!(7),
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            Some(&options)
        ).is_ok());
        assert!(c.compile_into_spirv(
            &texture_offset!(8),
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            Some(&options)
        ).is_err());
        options.set_limit(Limit::MaxProgramTexelOffset, 10);
        assert!(c.compile_into_spirv(
            &texture_offset!(8),
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            Some(&options)
        ).is_ok());
        assert!(c.compile_into_spirv(
            &texture_offset!(10),
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            Some(&options)
        ).is_ok());
        assert!(c.compile_into_spirv(
            &texture_offset!(11),
            ShaderKind::Fragment,
            "shader.glsl",
            "main",
            Some(&options)
        ).is_err());
    }

    #[test]
    fn test_compile_options_set_auto_bind_uniforms_false() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_auto_bind_uniforms(false);
        let result = c.compile_into_spirv_assembly(
            UNIFORMS_NO_BINDINGS,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        );
        assert!(result.is_err());
        assert_matches!(result.err(),
                        Some(Error::CompilationError(4, ref s))
                            if s.contains("error: 'binding' : sampler/texture/image requires layout(binding=X)"));
    }

    #[test]
    fn test_compile_options_set_auto_bind_uniforms_true() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_auto_bind_uniforms(true);
        let result = c.compile_into_spirv_assembly(
            UNIFORMS_NO_BINDINGS,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap()
            .as_text();
        assert!(result.contains("OpDecorate %my_tex Binding 0"));
        assert!(result.contains("OpDecorate %my_sam Binding 1"));
        assert!(result.contains("OpDecorate %my_img Binding 2"));
        assert!(result.contains("OpDecorate %my_imbuf Binding 3"));
        assert!(result.contains("OpDecorate %my_ubo Binding 4"));
    }

    #[test]
    fn test_compile_options_set_hlsl_offsets_false() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_hlsl_offsets(false);
        let result = c.compile_into_spirv_assembly(
            GLSL_WEIRD_PACKING,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap()
            .as_text();
        assert!(result.contains("OpMemberDecorate %B 1 Offset 16"));
    }

    #[test]
    fn test_compile_options_set_hlsl_offsets_true() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_hlsl_offsets(true);
        let result = c.compile_into_spirv_assembly(
            GLSL_WEIRD_PACKING,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap()
            .as_text();
        assert!(result.contains("OpMemberDecorate %B 1 Offset 4"));
    }

    #[test]
    fn test_compile_options_set_binding_base() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_auto_bind_uniforms(true);
        options.set_binding_base(ResourceKind::Image, 44);
        let result = c.compile_into_spirv_assembly(
            UNIFORMS_NO_BINDINGS,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap()
            .as_text();
        assert!(result.contains("OpDecorate %my_tex Binding 0"));
        assert!(result.contains("OpDecorate %my_sam Binding 1"));
        assert!(result.contains("OpDecorate %my_img Binding 44"));
        assert!(result.contains("OpDecorate %my_imbuf Binding 45"));
        assert!(result.contains("OpDecorate %my_ubo Binding 2"));
    }

    #[test]
    fn test_compile_options_set_binding_base_for_stage_effective() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_auto_bind_uniforms(true);
        options.set_binding_base_for_stage(ShaderKind::Vertex, ResourceKind::Texture, 100);
        let result = c.compile_into_spirv_assembly(
            UNIFORMS_NO_BINDINGS,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap()
            .as_text();
        assert!(result.contains("OpDecorate %my_tex Binding 100"));
        assert!(result.contains("OpDecorate %my_sam Binding 0"));
        assert!(result.contains("OpDecorate %my_img Binding 1"));
        assert!(result.contains("OpDecorate %my_imbuf Binding 2"));
        assert!(result.contains("OpDecorate %my_ubo Binding 3"));
    }

    #[test]
    fn test_compile_options_set_binding_base_for_stage_ignore() {
        let mut c = Compiler::new().unwrap();
        let mut options = CompileOptions::new().unwrap();
        options.set_auto_bind_uniforms(true);
        options.set_binding_base_for_stage(ShaderKind::Fragment, ResourceKind::Texture, 100);
        let result = c.compile_into_spirv_assembly(
            UNIFORMS_NO_BINDINGS,
            ShaderKind::Vertex,
            "shader.glsl",
            "main",
            Some(&options),
        ).unwrap()
            .as_text();
        assert!(result.contains("OpDecorate %my_tex Binding 0"));
        assert!(result.contains("OpDecorate %my_sam Binding 1"));
        assert!(result.contains("OpDecorate %my_img Binding 2"));
        assert!(result.contains("OpDecorate %my_imbuf Binding 3"));
        assert!(result.contains("OpDecorate %my_ubo Binding 4"));
    }

    #[test]
    fn test_error_compilation_error() {
        let mut c = Compiler::new().unwrap();
        let result =
            c.compile_into_spirv(TWO_ERROR, ShaderKind::Vertex, "shader.glsl", "main", None);
        assert!(result.is_err());
        assert_eq!(
            Some(Error::CompilationError(2, TWO_ERROR_MSG.to_string())),
            result.err()
        );
    }

    #[test]
    fn test_error_invalid_stage() {
        let mut c = Compiler::new().unwrap();
        let result = c.compile_into_spirv(
            VOID_MAIN,
            ShaderKind::InferFromSource,
            "shader.glsl",
            "main",
            None,
        );
        assert!(result.is_err());
        assert_eq!(Some(Error::InvalidStage("".to_string())), result.err());
    }

    #[test]
    fn test_warning() {
        let mut c = Compiler::new().unwrap();
        let result =
            c.compile_into_spirv(ONE_WARNING, ShaderKind::Vertex, "shader.glsl", "main", None)
                .unwrap();
        assert_eq!(1, result.get_num_warnings());
        assert_eq!(ONE_WARNING_MSG.to_string(), result.get_warning_messages());
    }

    #[test]
    fn test_get_spirv_version() {
        let (version, _) = get_spirv_version();
        assert_eq!((1 << 16) + (3 << 8), version);
    }

    #[test]
    fn test_parse_version_profile() {
        assert_eq!(Some((310, GlslProfile::Es)), parse_version_profile("310es"));
        assert_eq!(
            Some((450, GlslProfile::Compatibility)),
            parse_version_profile("450compatibility")
        );
        assert_eq!(Some((140, GlslProfile::None)), parse_version_profile("140"));
        assert_eq!(None, parse_version_profile("something"));
        assert_eq!(None, parse_version_profile(""));
    }
}